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
sebastianvarela/iOS-Swift-Helpers
Helpers/Helpers/IOSDevice.swift
2
1234
import UIKit import CryptoSwift public protocol Device { var osName: String { get } var osVersion: String { get } var deviceModel: String { get } var identifierForVendor: String { get } var footprint: String { get } } public struct IOSDevice: Device { public init() { } public var osName: String { return UIDevice.current.systemName } public var osVersion: String { return UIDevice.current.systemVersion } public var deviceModel: String { return UIDevice.current.deviceModel.name } public var identifierForVendor: String { guard let identifier = UIDevice.current.identifierForVendor?.uuidString else { fatalError("Identifier for vendor must exist") } return "\(identifier)" } public var footprint: String { let identifierForVendorSha256 = identifierForVendor.sha256() let modelSha256 = UIDevice.current.model.sha256() //Use current Model instead of fancy model. let systemNameSha256 = osName.sha256() let superHash = "\(identifierForVendorSha256)\(modelSha256)\(systemNameSha256)".sha256() return superHash.base64Encoded } }
mit
2097e2593815e78e74c7754758ca205b
27.045455
101
0.65235
5.036735
false
false
false
false
carabina/AppVersionChecker
AppVersionChecker/AppVersion.swift
1
3232
// // AppVersion.swift // AppVersionChecker // // Created by Hiroshi Kimura on 8/25/15. // Copyright © 2015 muukii. All rights reserved. // import Foundation public func >= (lhs: AppVersion, rhs: AppVersion) -> Bool { let lhs = lhs.versionString.characters.split(".").map { (String($0) as NSString).integerValue } let rhs = rhs.versionString.characters.split(".").map { (String($0) as NSString).integerValue } let count = max(lhs.count, rhs.count) for (r, l) in zip( lhs + Array(count: count - lhs.count, repeatedValue: 0), rhs + Array(count: count - rhs.count, repeatedValue: 0)) { print(l,r) if l < r { return true } else if l > r { return false } } return (lhs == rhs) } public func == (lhs: AppVersion, rhs: AppVersion) -> Bool { let lhs = lhs.versionString.characters.split(".").map { (String($0) as NSString).integerValue } let rhs = rhs.versionString.characters.split(".").map { (String($0) as NSString).integerValue } let count = max(lhs.count, rhs.count) var result: Bool = true for (l, r) in zip( lhs + Array(count: count - lhs.count, repeatedValue: 0), rhs + Array(count: count - rhs.count, repeatedValue: 0)) { if l != r { result = false } } return result } public func <= (lhs: AppVersion, rhs: AppVersion) -> Bool { let lhs = lhs.versionString.characters.split(".").map { (String($0) as NSString).integerValue } let rhs = rhs.versionString.characters.split(".").map { (String($0) as NSString).integerValue } let count = max(lhs.count, rhs.count) for (l, r) in zip( lhs + Array(count: count - lhs.count, repeatedValue: 0), rhs + Array(count: count - rhs.count, repeatedValue: 0)) { if l < r { return true } else if l > r { return false } } return (lhs == rhs) } public struct AppVersion: StringLiteralConvertible { public static var currentShortVersion: AppVersion { if let dic = NSBundle.mainBundle().infoDictionary { return AppVersion(dic["CFBundleShortVersionString"] as! String) } else { fatalError() } } public static var currentVersion: AppVersion { if let dic = NSBundle.mainBundle().infoDictionary { return AppVersion(dic[kCFBundleVersionKey as String] as! String) } else { fatalError() } } private(set) public var versionString: String public init(_ versionString: String) { self.versionString = versionString } // MARK: StringLiteralConvertible public init(stringLiteral value: String) { self.versionString = value } public init(unicodeScalarLiteral value: String) { self.versionString = value } public init(extendedGraphemeClusterLiteral value: String) { self.versionString = value } }
mit
3f0a217bcac8683d5563f20371feddb4
26.623932
99
0.557103
4.60913
false
false
false
false
SwiftyCache/SwiftyCache
Tests/LinkedDictionaryTests.swift
1
5788
// // LinkedDictionaryTests.swift // SwiftyCache // // Created by Haoming Ma on 22/03/2016. // // Copyright (C) 2016 SwiftyCache // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest @testable import SwiftyCache class Counter { var value: Int = 0 func increment() { self.value += 1 } func decrement() { self.value -= 1 } } class Str { var str: String var counter: Counter init(str: String, counter: Counter) { self.str = str self.counter = counter self.counter.increment() } deinit { print("Str deinit: \(str)") self.counter.decrement() } } func printDic(dic: LinkedDictionary<Int, Str>) { for (key, value) in dic { print("key: \(key), value: \(value.str)") } } class LinkedDictionaryTests: XCTestCase { private var dic: LinkedDictionary<Int, Str>! private var counter: Counter! override func setUp() { super.setUp() self.counter = Counter() self.dic = createDic(accessOrder: true); } private func createDic(accessOrder accessOrder: Bool) -> LinkedDictionary<Int, Str> { return LinkedDictionary<Int, Str>(dummyKey: 0, dummyValue: Str(str: "dummy", counter: self.counter), initialCapacity: 10, accessOrder: accessOrder) } func deinitDic() { self.dic = nil } override func tearDown() { self.deinitDic() XCTAssertTrue(self.counter.value == 0) super.tearDown() } func assertRemovedEldestEntry(key key: Int, value: String) { let (key1, value1) = self.dic.removeEldestEntry()! XCTAssertEqual(key, key1) XCTAssertEqual(value, value1.str) } func assertEldestEntry(key key: Int, value: String) { let (key1, value1) = self.dic.getEldestEntry()! XCTAssertEqual(key, key1) XCTAssertEqual(value, value1.str) } func testOrder() { self.dic = self.createDic(accessOrder: false) self.dic.updateValue(Str(str: "1", counter: self.counter), forKey: 1) self.dic.updateValue(Str(str: "2", counter: self.counter), forKey: 2) self.dic.updateValue(Str(str: "3", counter: self.counter), forKey: 3) //access 1 self.dic.touchKey(1) assertEldestEntry(key: 1, value: "1") assertRemovedEldestEntry(key: 1, value: "1") assertRemovedEldestEntry(key: 2, value: "2") assertRemovedEldestEntry(key: 3, value: "3") XCTAssertNil(self.dic.getEldestEntry()) XCTAssertNil(self.dic.removeEldestEntry()) self.dic = self.createDic(accessOrder: true) self.dic.updateValue(Str(str: "1", counter: self.counter), forKey: 1) self.dic.updateValue(Str(str: "2", counter: self.counter), forKey: 2) self.dic.updateValue(Str(str: "3", counter: self.counter), forKey: 3) //access 1 self.dic.touchKey(1) assertEldestEntry(key: 2, value: "2") assertRemovedEldestEntry(key: 2, value: "2") assertRemovedEldestEntry(key: 3, value: "3") assertRemovedEldestEntry(key: 1, value: "1") XCTAssertNil(self.dic.getEldestEntry()) XCTAssertNil(self.dic.removeEldestEntry()) } func testLinkedDictionaryWithAccessOrder() { dic.updateValue(Str(str: "1", counter: self.counter), forKey: 1) var old1 = dic.updateValue(Str(str: "new1", counter: self.counter), forKey: 1) XCTAssertEqual("1", old1!.str) old1 = nil print("--Str deinit: 1 here") dic.updateValue(Str(str: "2", counter: self.counter), forKey: 2) dic.updateValue(Str(str: "3", counter: self.counter), forKey: 3) dic.voidUpdateValue(Str(str: "new3", counter: self.counter), forKey: 3) print("--here comes Str deinit: 3") dic.updateValue(Str(str: "new2", counter: self.counter), forKey: 2) print("anonymous ref to key 2") print("--no Str deinit: 2 here") //print("touch key 2") var two: Str? // = dic.get(2) XCTAssertEqual(3, dic.count()) printDic(dic) two = dic.removeValueForKey(2) XCTAssertEqual(2, dic.count()) print("key 2 removed: \(two!.str)") two = nil print("--Str deinit: new2 should be here, but not, why???") printDic(dic) dic.touchKey(1) print("touch key 1") printDic(dic) dic.touchKey(3) print("touch key 3") printDic(dic) let (key1, entry1) = dic.getEldestEntry()! XCTAssertEqual(1, key1) let (keyOne, entryOne) = dic.removeEldestEntry()! print("removeEldestEntry key 1") XCTAssertEqual(1, keyOne) XCTAssertTrue(entry1 === entryOne) XCTAssertEqual(1, dic.count()) XCTAssertEqual("new3", dic.get(3)!.str) printDic(dic) dic.removeAll() print("after dic.removeAll()") print("test method exits") } }
apache-2.0
20c18a0e3ad6eeb1fbcadd2214676abe
28.085427
155
0.582585
4.102055
false
false
false
false
mshafer/stock-portfolio-ios
Portfolio/SearchBarViewController.swift
1
6220
// // SearchBarViewController.swift // Portfolio // // Created by Michael Shafer on 24/09/15. // Copyright © 2015 mshafer. All rights reserved. // import UIKit class SearchBarViewController: UITableViewController, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating { // MARK: - Properties var debounceTimer: NSTimer? var yahooStockQuoteService = YahooStockQuoteService() var editHoldingDelegate: EditHoldingDelegate? // `searchController` is set in viewDidLoad(_:). var searchController: UISearchController! var isLoading = false var searchResults: [StockSearchResult] = [] var filterString: String? = nil { didSet { if filterString == nil || filterString!.isEmpty { searchResults = [] self.tableView.reloadData() } else if (filterString != oldValue) { self.stageRefreshOperation() } } } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() // Create the search controller and make it perform the results updating. searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.delegate = self as UISearchControllerDelegate searchController.searchBar.delegate = self as UISearchBarDelegate searchController.hidesNavigationBarDuringPresentation = false searchController.dimsBackgroundDuringPresentation = false /* Configure the search controller's search bar. For more information on how to configure search bars, see the "Search Bar" group under "Search". */ searchController.searchBar.searchBarStyle = .Minimal searchController.searchBar.placeholder = NSLocalizedString("Search", comment: "") let textFieldInsideSearchBar = searchController.searchBar.valueForKey("searchField") as? UITextField textFieldInsideSearchBar?.textColor = UIColor.whiteColor() navigationController?.navigationBar.tintColor = UIColor.whiteColor() // Add a prompt above the navigationItem.prompt = "Type a company name or stock symbol" navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] // Include the search bar within the navigation bar. navigationItem.titleView = searchController.searchBar definesPresentationContext = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) searchController.active = true } func didPresentSearchController(searchController: UISearchController) { searchController.becomeFirstResponder() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } // MARK: - Data fetching /** Set a timer that when expired will refresh the search results. The timer only runs out if the user hasn't typed within some time threshold */ func stageRefreshOperation() { isLoading = true tableView.reloadData() if let timer = debounceTimer { timer.invalidate() } debounceTimer = NSTimer(timeInterval: 0.4, target: self, selector: Selector("refreshSearchResults"), userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(debounceTimer!, forMode: "NSDefaultRunLoopMode") } func refreshSearchResults() { if let filterString = self.filterString { yahooStockQuoteService.searchForStockSymbols(filterString, onCompletion: self.onRefreshSuccess, onError: self.onRefreshError) } } func onRefreshSuccess(results: [StockSearchResult]) { isLoading = false self.searchResults = results self.tableView.reloadData() } func onRefreshError() { isLoading = false } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isLoading { return 1 } else { return searchResults.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if isLoading { return tableView.dequeueReusableCellWithIdentifier("LoadingCell")! } let cell = tableView.dequeueReusableCellWithIdentifier("StockSearchResultCell", forIndexPath: indexPath) as! StockSearchResultTableViewCell cell.configureForSearchResult(searchResults[indexPath.row]) return cell } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowNewHoldingSegue" { if let indexPath = self.tableView.indexPathForSelectedRow { let searchResult = searchResults[indexPath.row] let controller = segue.destinationViewController as! NewHoldingViewController controller.stockSearchResult = searchResult controller.editHoldingDelegate = self.editHoldingDelegate controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - UISearchResultsUpdating func updateSearchResultsForSearchController(searchController: UISearchController) { guard searchController.active else { return } filterString = searchController.searchBar.text } // MARK: - Cleanup override func viewDidDisappear(animated: Bool) { if let timer = debounceTimer { timer.invalidate() } super.viewDidDisappear(animated) } }
gpl-3.0
5fe2d8abaa7f6d381fb1e01ca22cf8ba
35.162791
147
0.668435
6.151335
false
false
false
false
lixinxiu/nongjiahui-ios
农稼汇/AFNetworking-master/Example/tvOS Example/Gravatar.swift
20
3916
// Gravatar.swift // // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit private extension String { var md5_hash: String { let trimmedString = lowercaseString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let utf8String = trimmedString.cStringUsingEncoding(NSUTF8StringEncoding)! let stringLength = CC_LONG(trimmedString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLength = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength) CC_MD5(utf8String, stringLength, result) var hash = "" for i in 0..<digestLength { hash += String(format: "%02x", result[i]) } result.dealloc(digestLength) return String(format: hash) } } // MARK: - QueryItemConvertible private protocol QueryItemConvertible { var queryItem: NSURLQueryItem {get} } // MARK: - public struct Gravatar { public enum DefaultImage: String, QueryItemConvertible { case HTTP404 = "404" case MysteryMan = "mm" case Identicon = "identicon" case MonsterID = "monsterid" case Wavatar = "wavatar" case Retro = "retro" case Blank = "blank" var queryItem: NSURLQueryItem { return NSURLQueryItem(name: "d", value: rawValue) } } public enum Rating: String, QueryItemConvertible { case G = "g" case PG = "pg" case R = "r" case X = "x" var queryItem: NSURLQueryItem { return NSURLQueryItem(name: "r", value: rawValue) } } public let email: String public let forceDefault: Bool public let defaultImage: DefaultImage public let rating: Rating private static let baseURL = NSURL(string: "https://secure.gravatar.com/avatar")! public init( emailAddress: String, defaultImage: DefaultImage = .MysteryMan, forceDefault: Bool = false, rating: Rating = .PG) { self.email = emailAddress self.defaultImage = defaultImage self.forceDefault = forceDefault self.rating = rating } public func URL(size size: CGFloat, scale: CGFloat = UIScreen.mainScreen().scale) -> NSURL { let URL = Gravatar.baseURL.URLByAppendingPathComponent(email.md5_hash) let components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false)! var queryItems = [defaultImage.queryItem, rating.queryItem] queryItems.append(NSURLQueryItem(name: "f", value: forceDefault ? "y" : "n")) queryItems.append(NSURLQueryItem(name: "s", value: String(format: "%.0f",size * scale))) components.queryItems = queryItems return components.URL! } }
apache-2.0
cb0cf21ae626948cf9d2d9b47944aa5b
33.637168
116
0.6814
4.631953
false
false
false
false
CodePath2017Group4/travel-app
RoadTripPlanner/PlacesView.swift
1
3257
// // PlacesMarkerView.swift // RoadTripPlanner // // Created by Deepthy on 10/28/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit import MapKit class PlacesMarkerView: MKMarkerAnnotationView { override var annotation: MKAnnotation? { willSet { print("entered PlacesMarkerView =========>> willset") print("newValue \(newValue)") guard let places = newValue as? Places else { return } print("entered PlacesMarkerView =========>> annotation") print("entered type =========>> \(places.type!)") print("entered type condition =========>> \((places.type != "start" && places.type != "finish"))") canShowCallout = (places.type != "start" && places.type != "finish")//true calloutOffset = CGPoint(x: -5, y: 5) rightCalloutAccessoryView = UIButton(type: .detailDisclosure) markerTintColor = places.markerTintColor if (places.type != "start" && places.type != "finish") { glyphText = "\((places.type?.capitalized.first)!)" print("glyphText \(glyphText)") } else { if let imageName = places.imageName { glyphImage = UIImage(named: imageName) } else { glyphImage = nil } } } } } class PlaceMarkerView: MKMarkerAnnotationView { override var annotation: MKAnnotation? { willSet { guard let places = newValue as? Places else { return } canShowCallout = (places.type != "start" && places.type != "finish")//true calloutOffset = CGPoint(x: -5, y: 5) let mapsButton = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 30, height: 30))) mapsButton.setBackgroundImage(UIImage(named: "navigation"), for: UIControlState()) rightCalloutAccessoryView = mapsButton let detailLabel = UILabel() detailLabel.numberOfLines = 0 detailLabel.font = detailLabel.font.withSize(12) detailLabel.textColor = places.markerTintColor detailLabel.text = places.subtitle detailCalloutAccessoryView = detailLabel markerTintColor = places.markerTintColor if let imageName = places.imageName { glyphImage = UIImage(named: imageName) } else { glyphImage = nil } } } } class PlacesView: MKAnnotationView { override var annotation: MKAnnotation? { willSet { guard let places = newValue as? Places else {return} canShowCallout = true calloutOffset = CGPoint(x: -5, y: 5) rightCalloutAccessoryView = UIButton(type: .detailDisclosure) if let imageName = places.imageName { image = UIImage(named: imageName) } else { image = nil } } } }
mit
f91ede8b55af890f71f99ece7e668b4c
30.61165
112
0.523034
5.472269
false
false
false
false
Sumolari/OperationsKit
Tests/RetryableAsynchronousOperationTests.swift
1
14523
// // RetryableAsynchronousOperationTests.swift // Tests // // Created by Lluís Ulzurrun de Asanza Sàez on 10/2/17. // // import XCTest import OperationsKit import PromiseKit import Nimble class RetryableAsynchronousOperationTests: XCTestCase { // MARK: - Common fixtures /// Returns a queue properly set up to be used in tests. func queue() -> OperationQueue { let queue = OperationQueue() // Must be 1 to easily reason about lifecycle queue.maxConcurrentOperationCount = 1 queue.name = "\(type(of: self))" return queue } /** An operation which always repeat itself but each repetition is manually triggered. */ class ManualOperation: RetryableAsynchronousOperation<Void, BaseRetryableOperationError> { override func execute() throws { } } /// An operation which always repeat itself until reaching maximum attempts. class UnlimitedOperation: RetryableAsynchronousOperation<Void, BaseRetryableOperationError> { fileprivate let msToWait: Double init(msToWait: Double, maximumAttempts: UInt64) { self.msToWait = msToWait super.init(maximumAttempts: maximumAttempts) } override func execute() throws { usleep(UInt32(self.msToWait * 1000)) self.retry() } } /** An operation which always repeat itself until reaching maximum attempts, throwing a specific error on each repetition. */ class FailedOperation: RetryableAsynchronousOperation<Void, BaseRetryableOperationError> { fileprivate let constant: Swift.Error init(constant: Swift.Error, maximumAttempts: UInt64) { self.constant = constant super.init(maximumAttempts: maximumAttempts) } override func execute() throws { self.retry(dueTo: self.constant) } } /** An operation which will throw a specific error. */ class ThrowingOperation: RetryableAsynchronousOperation<Void, BaseRetryableOperationError> { fileprivate let constant: Swift.Error fileprivate let afterAttempts: UInt64 init(constant: Swift.Error, afterAttempts: UInt64, maximumAttempts: UInt64) { self.constant = constant self.afterAttempts = afterAttempts super.init(maximumAttempts: maximumAttempts) } override func execute() throws { guard self.attempts >= self.afterAttempts else { return self.retry(dueTo: self.constant) } throw self.constant } } // MARK: - Test lifecycle override func setUp() { super.setUp() // Put setup code here. // This method is called before the invocation of each test method in // the class. } override func tearDown() { // Put teardown code here. // This method is called after the invocation of each test method in the // class. super.tearDown() } // MARK: - Tests func test__operation_reaches_retry_limit() { let attempts: UInt64 = 3 let op = UnlimitedOperation(msToWait: 1, maximumAttempts: attempts) self.queue().addOperation(op) let errorExpected = BaseRetryableOperationError.ReachedRetryLimit // Operation must be finished, eventually. expect(op.isFinished).toEventually(beTrue()) // Operation enqueued status must be finished, eventually. expect(op.status).toEventually(equal(OperationStatus.finished)) // Promise must be resolved, eventually. expect(op.promise.isResolved).toEventually(beTrue()) // Promise must not be fulfilled, ever. expect(op.promise.isFulfilled).toNotEventually(beTrue()) // Promise must be rejected, eventually. expect(op.promise.isRejected).toEventually(beTrue()) // Promise must be rejected with expected error. expect(op.promise.error).toEventually(matchError(errorExpected)) // Operation's result must be the expected error, too. expect(op.result?.error).toEventually(matchError(errorExpected)) } func test__operation_retries_until_succeeds() { let attempts: UInt64 = 3 let op = ManualOperation(maximumAttempts: attempts) self.queue().addOperation(op) // Operation must be executing, eventually. expect(op.isExecuting).toEventually(beTrue()) // We do this twice. for _ in 0..<(attempts - 1) { // Operation must not be finished. expect(op.isFinished).to(beFalse()) // Operation must be executing. expect(op.isExecuting).to(beTrue()) // Operation enqueued status must be executing. expect(op.status).to(equal(OperationStatus.executing)) // Operation promise must not be resolved. expect(op.promise.isResolved).to(beFalse()) // Operation result must be nil. expect(op.result).to(beNil()) // We retry the operation. op.retry() } op.finish() // Operation must be finished, eventually. expect(op.isFinished).toEventually(beTrue()) // Operation enqueued status must be finished, eventually. expect(op.status).toEventually(equal(OperationStatus.finished)) // Operation promise must be resolved, eventually. expect(op.promise.isResolved).toEventually(beTrue()) // Operation promise must be fulfilled, eventually. expect(op.promise.isFulfilled).toEventually(beTrue()) // Operation promise must be fulfilled with expected value, eventually. expect(op.promise.value).toEventually(beVoid()) // Operation result must be expected value, too, eventually. expect(op.result?.value).toEventually(beVoid()) } func test__canceled_operation_is_not_retried() { let attempts: UInt64 = 3 let op = ManualOperation(maximumAttempts: attempts) let errorExpected = BaseRetryableOperationError.Cancelled self.queue().addOperation(op) // Operation attempts must match expected value. expect(op.attempts).to(equal(0)) // We retry the operation. op.retry() // Operation attempts must match expected value. expect(op.attempts).to(equal(1)) // We cancel. op.cancel() // Operation attempts must match expected value. expect(op.attempts).to(equal(1)) // We retry the operation. op.retry() // Operation attempts must match expected value. expect(op.attempts).to(equal(1)) // Operation must be resolved with proper error. expect(op.promise.error).to(matchError(errorExpected)) // Operation result must be proper error, too. expect(op.result?.error).to(matchError(errorExpected)) } func test__throwing_operation_is_not_retried() { let expectedError = NSError(domain: "expected", code: -1, userInfo: nil) let attempts: UInt64 = 3 let op = ThrowingOperation( constant: expectedError, afterAttempts: 0, maximumAttempts: attempts ) let queue = self.queue() queue.isSuspended = true queue.addOperation(op) // Operation attempts must match expected value. expect(op.attempts).to(equal(0)) // Operation must not be finished. expect(op.isFinished).to(beFalse()) // Operation must be ready to be run. expect(op.status).to(equal(OperationStatus.ready)) queue.isSuspended = false // Operation attempts must match expected value, eventually. expect(op.attempts).toEventually(equal(0)) // Promise must be rejected with expected error... // - Promise must be rejected with a `BaseOperationError` error... expect(op.isFinished).toEventually(beTrue()) // Wait until finishes... if let promiseError = op.promise.error as? BaseRetryableOperationError { // - Error must be `unknown`... switch promiseError { case .unknown(let underlyingError): // - Underlying error must match expected `NSError`... expect(underlyingError).to(matchError(expectedError)) default: XCTFail("Promise error must be `unknown`") } } else { XCTFail("Promise error must be a `BaseRetryableOperationError` instance") } // Operation's result must be the expected error, too... if let error = op.result?.error { // - Error must be `unknown`... switch error { case .unknown(let underlyingError): // - Underlying error must match expected `NSError`... expect(underlyingError).to(matchError(expectedError)) default: XCTFail("Result error must be `unknown`") } } else { XCTFail("Result error must be a `BaseRetryableOperationError` instance") } } func test__throwing_operation_is_retried_until_exception_thrown() { let expectedError = NSError(domain: "expected", code: -1, userInfo: nil) let attempts: UInt64 = 3 let op = ThrowingOperation( constant: expectedError, afterAttempts: 1, maximumAttempts: attempts ) let queue = self.queue() queue.isSuspended = true queue.addOperation(op) // Operation attempts must match expected value. expect(op.attempts).to(equal(0)) // Operation must not be finished. expect(op.isFinished).to(beFalse()) // Operation must be ready to be run. expect(op.status).to(equal(OperationStatus.ready)) queue.isSuspended = false // Operation attempts must match expected value, eventually. expect(op.attempts).toEventually(equal(1)) // Promise must be rejected with expected error... // - Promise must be rejected with a `BaseOperationError` error... expect(op.isFinished).toEventually(beTrue()) // Wait until finishes... if let promiseError = op.promise.error as? BaseRetryableOperationError { // - Error must be `unknown`... switch promiseError { case .unknown(let underlyingError): // - Underlying error must match expected `NSError`... expect(underlyingError).to(matchError(expectedError)) default: XCTFail("Promise error must be `unknown`") } } else { XCTFail("Promise error must be a `BaseRetryableOperationError` instance") } // Operation's result must be the expected error, too... if let error = op.result?.error { // - Error must be `unknown`... switch error { case .unknown(let underlyingError): // - Underlying error must match expected `NSError`... expect(underlyingError).to(matchError(expectedError)) default: XCTFail("Result error must be `unknown`") } } else { XCTFail("Result error must be a `BaseRetryableOperationError` instance") } } func test__operation_retry_count_is_updated() { let attempts: UInt64 = 3 let op = ManualOperation(maximumAttempts: attempts) self.queue().addOperation(op) // We do this twice. for currentAttempt in 0..<attempts { // Operation attempts must match expected value. expect(op.attempts).to(equal(currentAttempt)) // We retry the operation. op.retry() } expect(op.attempts).to(equal(attempts)) } /** Tests that a retryable asynchronous operation with a generic NSError properly fails wrapping the error in an unknown error. */ func test__result_fail_generic_error() { let expectedError = NSError(domain: "error", code: -1, userInfo: nil) let op = FailedOperation(constant: expectedError, maximumAttempts: 3) self.queue().addOperation(op) // Promise must resolve, eventually. expect(op.promise.isResolved).toEventually(beTrue()) // Promise must not be fulfilled, ever. expect(op.promise.isFulfilled).toNotEventually(beTrue()) // Promise must be rejected, eventually. expect(op.promise.isRejected).toEventually(beTrue()) // Promise must be rejected with expected error... // - Promise must be rejected with a `BaseOperationError` error... expect(op.isFinished).toEventually(beTrue()) // Wait until finishes... if let promiseError = op.promise.error as? BaseRetryableOperationError { // - Error must be `unknown`... switch promiseError { case .unknown(let underlyingError): // - Underlying error must match expected `NSError`... expect(underlyingError).to(matchError(expectedError)) default: XCTFail("Promise error must be `unknown`") } } else { XCTFail("Promise error must be a `BaseRetryableOperationError` instance") } // Operation's result must be the expected error, too... if let error = op.result?.error { // - Error must be `unknown`... switch error { case .unknown(let underlyingError): // - Underlying error must match expected `NSError`... expect(underlyingError).to(matchError(expectedError)) default: XCTFail("Result error must be `unknown`") } } else { XCTFail("Result error must be a `BaseRetryableOperationError` instance") } // Operation enqueued status must be finished, eventually. expect(op.status).toEventually(equal(OperationStatus.finished)) } }
mit
9c17afb869b8de5402e040b49cb1e930
36.716883
97
0.600303
5.261232
false
false
false
false
actilot/tesseract-swift
Source/Tesseract/Geometry.swift
1
2550
// // Geometry.swift // Tesseract // // Created by Axel Ros Campaña on 9/14/17. // Copyright © 2017 Axel Ros Campaña. All rights reserved. // /** This is a Swift version of Benihime, https://github.com/shiki/ios-benihime/blob/master/Benihime/BCGeometry.h */ import Foundation public func CGRectSetWidth(_ width: CGFloat, toRect rect: CGRect) -> CGRect { return CGRect(x: rect.origin.x, y: rect.origin.y, width: width, height: rect.size.height) } public func CGRectSetHeight(_ height: CGFloat, toRect rect: CGRect) -> CGRect { return CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: height) } public func CGRectSetSize(_ size: CGSize, toRect rect: CGRect) -> CGRect { return CGRect(x: rect.origin.x, y: rect.origin.y, width: size.width, height: size.height) } public func CGRectSetX(_ x: CGFloat, toRect rect: CGRect) -> CGRect { return CGRect(x: x, y: rect.origin.y, width: rect.size.width, height: rect.size.height) } public func CGRectSetY(_ y: CGFloat, toRect rect: CGRect) -> CGRect { return CGRect(x: rect.origin.x, y: y, width: rect.size.width, height: rect.size.height) } public func CGRectSetOrigin(_ origin: CGPoint, toRect rect: CGRect) -> CGRect { return CGRect(x: origin.x, y: origin.y, width: rect.size.width, height: rect.size.height) } public func CGRectSetOriginToCenter(containerRect container: CGRect, rect: CGRect) -> CGRect { let center = CGPoint(x: container.midX, y: container.midY) return CGRect(x: center.x - rect.size.width * 0.5, y: center.y - rect.size.height * 0.5, width: rect.size.width, height: rect.size.height) } public func CGRectAdd(x: CGFloat = 0, y: CGFloat = 0, width: CGFloat = 0, height: CGFloat = 0, toRect rect: CGRect) -> CGRect { return CGRect(x: rect.origin.x + x, y: rect.origin.y + y, width: rect.size.width + width, height: rect.size.height + height) } public func CGRectExpand(x: CGFloat, y: CGFloat, rect: CGRect) -> CGRect { let origin = rect.origin let size = rect.size return CGRect(x: origin.x - x / 2, y: origin.y - y / 2, width: size.width + x, height: size.height + y) } public func CGDegreesToRadians(_ degrees: CGFloat) -> CGFloat { return degrees * CGFloat.pi / 180 } public func CGRadiansToDegrees(_ radians: CGFloat) -> CGFloat { return radians * 180 / CGFloat.pi } public func CGNormalizedDegrees(_ degrees: CGFloat) -> CGFloat { var degrees = fmodf(Float(degrees), 360.0) if degrees < 0 { degrees += 360.0 } return CGFloat(degrees) }
mit
aa2ee907eee695248c41051aeb3755b8
35.385714
128
0.682371
3.303502
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/User/SettingViewController.swift
1
4837
// // SettingViewController.swift // viossvc // // Created by 木柳 on 2016/11/27. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD class SettingViewController: BaseTableViewController { @IBOutlet weak var userNumLabel: UILabel! @IBOutlet weak var authLabel: UILabel! @IBOutlet weak var authCell: UITableViewCell! @IBOutlet weak var cacheLabel: UILabel! @IBOutlet weak var versionLabel: UILabel! @IBOutlet weak var aboutUSCell: UITableViewCell! @IBOutlet weak var cacheCell: UITableViewCell! @IBOutlet weak var versionCell: UITableViewCell! var authStatus: String? { get{ switch CurrentUserHelper.shared.userInfo.auth_status_ { case -1: return "未认证" case 0: return "认证中" case 1: return "认证通过" case 2: return "认证失败" default: return "" } } } //MARK: --LIFECYCLE override func viewDidLoad() { super.viewDidLoad() initUI() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) authLabel.text = authStatus authCell.accessoryType = authStatus == "未认证" ? .DisclosureIndicator : .None } //MARK: --UI func initUI() { let userNum = CurrentUserHelper.shared.userInfo.phone_num! as NSString userNumLabel.text = userNum.stringByReplacingCharactersInRange(NSRange.init(location: 4, length: 4), withString: "****") //缓存 cacheLabel.text = String(format:"%.2f M",Double(calculateCacle())) authLabel.text = authStatus authCell.accessoryType = authStatus == "未认证" ? .DisclosureIndicator : .None } @IBAction func logoutBtnTapped(sender: AnyObject) { MobClick.event(AppConst.Event.user_logout) CurrentUserHelper.shared.logout() let rootController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginNavigationController") UIApplication.sharedApplication().keyWindow!.rootViewController = rootController } // 计算缓存 func calculateCacle() ->Double { let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first let files = NSFileManager.defaultManager().subpathsAtPath(path!) var size = 0.00 for file in files! { let filePath = path?.stringByAppendingString("/\(file)") let fileAtrributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(filePath!) for (attrKey,attrVale) in fileAtrributes { if attrKey == NSFileSize { size += attrVale.doubleValue } } } let totalSize = size/1024/1024 return totalSize } // 清除缓存 func clearCacleSizeCompletion(completion: (()->Void)?) { let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first let files = NSFileManager.defaultManager().subpathsAtPath(path!) for file in files! { let filePath = path?.stringByAppendingString("/\(file)") if NSFileManager.defaultManager().fileExistsAtPath(filePath!) { do{ try NSFileManager.defaultManager().removeItemAtPath(filePath!) }catch{ } } } completion!() } //MARK: --TableView override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cell = tableView.cellForRowAtIndexPath(indexPath) if cell == cacheCell{ MobClick.event(AppConst.Event.user_clearcache) clearCacleSizeCompletion({ [weak self] in self?.cacheLabel.text = String(format:"%.2f M",Double(self!.calculateCacle())) SVProgressHUD.showSuccessMessage(SuccessMessage: "清除成功", ForDuration: 1, completion: nil) }) return } if cell == authCell && (authStatus == "未认证" || authStatus == "认证失败"){ performSegueWithIdentifier("AuthUserViewController", sender: nil) return } if cell == versionCell { MobClick.event(AppConst.Event.user_version) } if cell == aboutUSCell{ UIApplication.sharedApplication().openURL(NSURL.init(string: "http://www.yundiantrip.com/")!) return } } }
apache-2.0
b236c5bf9e9282911900dbebe6b0595a
36.385827
144
0.614364
5.252212
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/Filters/CustomFilterViews/Price/PriceFilterView.swift
1
3263
import UIKit @objc protocol PriceFilterViewDelegate: NSObjectProtocol { func filterApplied() } @objcMembers @IBDesignable class PriceFilterView: UIView, HLRangeSliderDelegate { @IBOutlet weak var slider: HLRangeSlider! @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! weak var delegate: PriceFilterViewDelegate? private var sliderCalculator: HLPriceSliderCalculator? var filter: Filter? let appearanceDuration: TimeInterval = 0.5 override func awakeFromNib() { super.awakeFromNib() initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) initialize() } func configure(withFilter filter: Filter) { self.filter = filter updateRangeValueLabel(filter) sliderCalculator = filter.priceSliderCalculator guard sliderCalculator != nil else { return } slider.lowerValue = filter.graphSliderMinValue slider.upperValue = filter.graphSliderMaxValue updateRangeValueLabel(filter) } // MARK: - Private private func initialize() { let view = loadViewFromNib("PriceFilterView", self)! view.frame = bounds view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.clear addSubview(view) view.autoPinEdgesToSuperviewEdges() slider.trackBackgroundImage = JRColorScheme.sliderMinImage() slider.trackImage = JRColorScheme.sliderMaxImage() slider.lowerHandleImageNormal = UIImage(named: "JRSliderImg") slider.upperHandleImageNormal = UIImage(named: "JRSliderImg") slider.addTarget(self, action: #selector(sliderEditingDidEnd), for: .editingDidEnd) slider.delegate = self titleLabel.text = NSLS("HL_LOC_FILTER_PRICE_CRITERIA") } func sliderValueChanged() { filter?.graphSliderMinValue = slider.lowerValue filter?.graphSliderMaxValue = slider.upperValue updateRangeValueLabel(filter!) } @objc func sliderEditingDidEnd() { delegate?.filterApplied() } fileprivate func updateRangeValueLabel(_ filter: Filter) { valueLabel.attributedText = StringUtils.attributedRangeValueText(currency: filter.searchInfo.currency, minValue:Float(filter.currentMinPrice), maxValue: Float(filter.currentMaxPrice)) let sliderWidth = slider.bounds.width == 0 ? 1.0 : slider.bounds.width - slider.rangeSliderHorizontalOffset * 2 layoutIfNeeded() let linearSpace = slider.lowerHandle.bounds.width var lowerGraphValue = slider.lowerCenter.x - slider.rangeSliderHorizontalOffset if lowerGraphValue < linearSpace { lowerGraphValue += (lowerGraphValue - linearSpace) / 2 } var upperGraphValue = slider.upperCenter.x - slider.rangeSliderHorizontalOffset if upperGraphValue > sliderWidth - linearSpace { upperGraphValue += (linearSpace - sliderWidth + upperGraphValue) / 2 } } func minValueChanged() { sliderValueChanged() } func maxValueChanged() { sliderValueChanged() } }
mit
3290ee4b5e1316f3687651fd0a2bb454
29.212963
191
0.68863
5.058915
false
false
false
false
avito-tech/Marshroute
Example/NavigationDemo/VIPER/Authorization/View/AuthorizationView.swift
1
2500
import UIKit final class AuthorizationView: UIView { private let backgroundImage = UIImage(named: "TouchId.png") private let backgroundView: UIImageView? private let emailTextField = UITextField() private let passwordTextField = UITextField() // MARK: - Internal var defaultContentInsets: UIEdgeInsets = .zero // MARK: - Init init() { backgroundView = UIImageView(image: backgroundImage) super.init(frame: .zero) backgroundColor = .white backgroundView?.contentMode = .scaleAspectFit if let backgroundView = backgroundView { addSubview(backgroundView) backgroundView.contentMode = .center } addSubview(emailTextField) emailTextField.isUserInteractionEnabled = false emailTextField.text = " [email protected] " emailTextField.backgroundColor = UIColor.red.withAlphaComponent(0.1) addSubview(passwordTextField) passwordTextField.isUserInteractionEnabled = false passwordTextField.text = "......................." passwordTextField.isSecureTextEntry = true passwordTextField.backgroundColor = UIColor.red.withAlphaComponent(0.1) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() let topLayoutGuide = defaultContentInsets.top let centerX = bounds.midX let textFieldWidth: CGFloat = 240 let textFieldHeigth: CGFloat = 44 let textFieldSpaceY: CGFloat = 10 emailTextField.frame = CGRect( x: 0, y: topLayoutGuide + textFieldSpaceY, width: textFieldWidth, height: textFieldHeigth ) emailTextField.center.x = centerX passwordTextField.frame = CGRect( x: 0, y: emailTextField.frame.maxY + textFieldSpaceY, width: textFieldWidth, height: textFieldHeigth ) passwordTextField.center.x = centerX let backgroundViewMinY = passwordTextField.frame.maxY + 40 backgroundView?.frame = CGRect( x: 0, y: backgroundViewMinY, width: bounds.width, height: bounds.maxY - backgroundViewMinY - 40 ) } }
mit
dd71b8adba712c923c7b9f0bce63a51c
30.64557
79
0.6024
5.813953
false
false
false
false
brentdax/swift
test/SILOptimizer/unused_containers.swift
1
1494
// RUN: %target-swift-frontend -primary-file %s -O -emit-sil | grep -v 'builtin "onFastPath"' | %FileCheck %s // REQUIRES: swift_stdlib_no_asserts // FIXME: https://bugs.swift.org/browse/SR-7806 // REQUIRES: CPU=arm64 || CPU=x86_64 //CHECK-LABEL: @$s17unused_containers16empty_array_testyyF //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func empty_array_test() { let unused : [Int] = [] } //CHECK-LABEL: @$s17unused_containers14empty_dic_testyyF //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func empty_dic_test() { let unused : [Int: Int] = [:] } //CHECK-LABEL: sil hidden @$s17unused_containers0A12_string_testyyF //CHECK-NEXT: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func unused_string_test() { let unused : String = "" } //CHECK-LABEL: array_of_strings_test //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func array_of_strings_test() { let x = [""] } //CHECK-LABEL: string_interpolation //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func string_interpolation() { // Int let x : Int = 2 "\(x)" // String let y : String = "hi" "\(y)" // Float let f : Float = 2.0 "\(f)" // Bool "\(true)" //UInt8 "\(UInt8(2))" //UInt32 "\(UInt32(4))" } //CHECK-LABEL: string_interpolation2 //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func string_interpolation2() { "\(false) \(true)" } //CHECK-LABEL: string_plus //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func string_plus() { "a" + "b" }
apache-2.0
ca94ee9a7ca7c8a2d1bdd6d273f450be
17.444444
109
0.637885
2.808271
false
true
false
false
ja-mes/experiments
iOS/Swaping screens/Swaping screens/AppDelegate.swift
1
4590
// // AppDelegate.swift // Swaping screens // // Created by James Brown on 8/12/16. // Copyright © 2016 James Brown. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Swaping_screens") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
048d85f7f3ac082d2f92e059400e1ea9
48.344086
285
0.685117
5.831004
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderMenuViewController.swift
1
21697
import Foundation import CocoaLumberjack import Gridicons import WordPressShared /// The menu for the reader. /// @objc class ReaderMenuViewController: UITableViewController, UIViewControllerRestoration { static let restorationIdentifier = "ReaderMenuViewController" static let selectedIndexPathRestorationIdentifier = "ReaderMenuSelectedIndexPathKey" static let currentReaderStreamIdentifier = "ReaderMenuCurrentStream" let defaultCellIdentifier = "DefaultCellIdentifier" let actionCellIdentifier = "ActionCellIdentifier" let manageCellIdentifier = "ManageCellIdentifier" var isSyncing = false var didSyncTopics = false var currentReaderStream: ReaderStreamViewController? fileprivate var defaultIndexPath: IndexPath { return viewModel.indexPathOfDefaultMenuItemWithOrder(order: .followed) } fileprivate var restorableSelectedIndexPath: IndexPath? lazy var viewModel: ReaderMenuViewModel = { let vm = ReaderMenuViewModel() vm.delegate = self return vm }() /// A convenience method for instantiating the controller. /// /// - Returns: An instance of the controller. /// static func controller() -> ReaderMenuViewController { return ReaderMenuViewController(style: .grouped) } // MARK: - Restoration Methods static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { return WPTabBarController.sharedInstance().readerMenuViewController } override func encodeRestorableState(with coder: NSCoder) { coder.encode(restorableSelectedIndexPath, forKey: type(of: self).selectedIndexPathRestorationIdentifier) coder.encode(currentReaderStream, forKey: type(of: self).currentReaderStreamIdentifier) super.encodeRestorableState(with: coder) } override func decodeRestorableState(with coder: NSCoder) { decodeRestorableSelectedIndexPathWithCoder(coder: coder) decodeRestorableCurrentStreamWithCoder(coder: coder) super.decodeRestorableState(with: coder) } fileprivate func decodeRestorableSelectedIndexPathWithCoder(coder: NSCoder) { if let indexPath = coder.decodeObject(forKey: type(of: self).selectedIndexPathRestorationIdentifier) as? IndexPath { restorableSelectedIndexPath = indexPath } } fileprivate func decodeRestorableCurrentStreamWithCoder(coder: NSCoder) { if let currentStream = coder.decodeObject(forKey: type(of: self).currentReaderStreamIdentifier) as? ReaderStreamViewController { currentReaderStream = currentStream } } // MARK: - Lifecycle Methods deinit { NotificationCenter.default.removeObserver(self) } override init(style: UITableViewStyle) { super.init(style: style) // Need to use `super` to work around a Swift compiler bug // https://bugs.swift.org/browse/SR-3465 super.restorationIdentifier = ReaderMenuViewController.restorationIdentifier restorationClass = ReaderMenuViewController.self clearsSelectionOnViewWillAppear = false if restorableSelectedIndexPath == nil { restorableSelectedIndexPath = defaultIndexPath } setupRefreshControl() setupAccountChangeNotificationObserver() setupApplicationWillTerminateNotificationObserver() } required convenience init() { self.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Reader", comment: "") configureTableView() syncTopics() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // We shouldn't show a selection if our split view is collapsed if splitViewControllerIsHorizontallyCompact { animateDeselectionInteractively() restorableSelectedIndexPath = defaultIndexPath } reloadTableViewPreservingSelection() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) reloadTableViewPreservingSelection() } // MARK: - Configuration func setupRefreshControl() { if refreshControl != nil { return } refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(type(of: self).syncTopics), for: .valueChanged) } func setupApplicationWillTerminateNotificationObserver() { NotificationCenter.default.addObserver(self, selector: #selector(type(of: self).handleApplicationWillTerminate), name: NSNotification.Name.UIApplicationWillTerminate, object: nil) } func setupAccountChangeNotificationObserver() { NotificationCenter.default.addObserver(self, selector: #selector(type(of: self).handleAccountChanged), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil) } func configureTableView() { tableView.register(WPTableViewCell.self, forCellReuseIdentifier: defaultCellIdentifier) tableView.register(WPTableViewCell.self, forCellReuseIdentifier: actionCellIdentifier) WPStyleGuide.configureColors(for: view, andTableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) } // MARK: - Cleanup Methods /// Clears the inUse flag from any topics or posts so marked. /// func unflagInUseContent() { let context = ContextManager.sharedInstance().mainContext ReaderPostService(managedObjectContext: context).clearInUseFlags() ReaderTopicService(managedObjectContext: context).clearInUseFlags() } /// Clean up topics that do not belong in the menu and posts that have no topic /// This is merely a convenient place to perform this task. /// func cleanupStaleContent(removeAllTopics removeAll: Bool) { let context = ContextManager.sharedInstance().mainContext ReaderPostService(managedObjectContext: context).deletePostsWithNoTopic() if removeAll { ReaderTopicService(managedObjectContext: context).deleteAllTopics() } else { ReaderTopicService(managedObjectContext: context).deleteNonMenuTopics() } } // MARK: - Instance Methods /// Handle the UIApplicationWillTerminate notification. // func handleApplicationWillTerminate(_ notification: Foundation.Notification) { // Its important to clean up stale content before unflagging, otherwise // content we want to preserve for state restoration might also be // deleted. cleanupStaleContent(removeAllTopics: false) unflagInUseContent() } /// When logged out return the nav stack to the menu /// func handleAccountChanged(_ notification: Foundation.Notification) { // Reset the selected index path restorableSelectedIndexPath = defaultIndexPath // Clean up obsolete content. unflagInUseContent() cleanupStaleContent(removeAllTopics: true) // Clean up stale search history let context = ContextManager.sharedInstance().mainContext ReaderSearchSuggestionService(managedObjectContext: context).deleteAllSuggestions() // Sync the menu fresh syncTopics() } /// Sync the Reader's menu /// func syncTopics() { if isSyncing { return } isSyncing = true let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.fetchReaderMenu(success: { [weak self] in self?.didSyncTopics = true self?.cleanupAfterSync() }, failure: { [weak self] (error) in self?.cleanupAfterSync() DDLogError("Error syncing menu: \(String(describing: error))") }) } /// Reset's state after a sync. /// func cleanupAfterSync() { refreshControl?.endRefreshing() isSyncing = false } /// Presents the detail view controller for the specified post on the specified /// blog. This is a convenience method for use with Notifications (for example). /// /// - Parameters: /// - postID: The ID of the post on the specified blog. /// - blogID: The ID of the blog. /// func openPost(_ postID: NSNumber, onBlog blogID: NSNumber) { let controller = ReaderDetailViewController.controllerWithPostID(postID, siteID: blogID) navigationController?.pushFullscreenViewController(controller, animated: true) } /// Presents the post list for the specified topic. /// /// - Parameters: /// - topic: The topic to show. /// func showPostsForTopic(_ topic: ReaderAbstractTopic) { showDetailViewController(viewControllerForTopic(topic), sender: self) } fileprivate func viewControllerForTopic(_ topic: ReaderAbstractTopic) -> ReaderStreamViewController { return ReaderStreamViewController.controllerWithTopic(topic) } /// Presents the reader's search view controller. /// func showReaderSearch() { showDetailViewController(viewControllerForSearch(), sender: self) } fileprivate func viewControllerForSearch() -> ReaderSearchViewController { return ReaderSearchViewController.controller() } /// Presents a new view controller for subscribing to a new tag. /// func showAddTag() { let placeholder = NSLocalizedString("Add any tag", comment: "Placeholder text. A call to action for the user to type any tag to which they would like to subscribe.") let controller = SettingsTextViewController(text: nil, placeholder: placeholder, hint: nil) controller.title = NSLocalizedString("Add a Tag", comment: "Title of a feature to add a new tag to the tags subscribed by the user.") controller.onValueChanged = { value in if value.trim().count > 0 { self.followTagNamed(value.trim()) } } controller.mode = .lowerCaseText controller.displaysActionButton = true controller.actionText = NSLocalizedString("Add Tag", comment: "Button Title. Tapping subscribes the user to a new tag.") controller.onActionPress = { self.dismissModal() } let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ReaderMenuViewController.dismissModal)) controller.navigationItem.leftBarButtonItem = cancelButton let navController = UINavigationController(rootViewController: controller) navController.modalPresentationStyle = .formSheet present(navController, animated: true, completion: nil) } /// Dismisses a presented view controller. /// func dismissModal() { dismiss(animated: true, completion: nil) } // MARK: - Tag Wrangling /// Prompts the user to confirm unfolowing a tag. /// /// - Parameters: /// - topic: The tag topic that is to be unfollowed. /// func promptUnfollowTagTopic(_ topic: ReaderTagTopic) { let title = NSLocalizedString("Remove", comment: "Title of a prompt asking the user to confirm they no longer wish to subscribe to a certain tag.") let template = NSLocalizedString("Are you sure you wish to remove the tag '%@'?", comment: "A short message asking the user if they wish to unfollow the specified tag. The %@ is a placeholder for the name of the tag.") let message = String(format: template, topic.title) let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addCancelActionWithTitle(NSLocalizedString("Cancel", comment: "Title of a cancel button.")) { (action) in self.tableView.setEditing(false, animated: true) } alert.addDestructiveActionWithTitle(NSLocalizedString("Remove", comment: "Verb. Button title. Unfollows / unsubscribes the user from a topic in the reader.")) { (action) in self.unfollowTagTopic(topic) } alert.presentFromRootViewController() } /// Tells the ReaderTopicService to unfollow the specified topic. /// /// - Parameters: /// - topic: The tag topic that is to be unfollowed. /// func unfollowTagTopic(_ topic: ReaderTagTopic) { let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.unfollowTag(topic, withSuccess: nil) { (error) in DDLogError("Could not unfollow topic \(topic), \(String(describing: error))") let title = NSLocalizedString("Could Not Remove Tag", comment: "Title of a prompt informing the user there was a probem unsubscribing from a tag in the reader.") let message = error?.localizedDescription let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addCancelActionWithTitle(NSLocalizedString("OK", comment: "Button title. An acknowledgement of the message displayed in a prompt.")) alert.presentFromRootViewController() } } /// Follow a new tag with the specified tag name. /// /// - Parameters: /// - tagName: The name of the tag to follow. /// func followTagNamed(_ tagName: String) { let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext) let generator = UINotificationFeedbackGenerator() generator.prepare() service.followTagNamed(tagName, withSuccess: { [weak self] in generator.notificationOccurred(.success) // A successful follow makes the new tag the currentTopic. if let tag = service.currentTopic as? ReaderTagTopic { self?.scrollToTag(tag) } }, failure: { (error) in DDLogError("Could not follow tag named \(tagName) : \(String(describing: error))") generator.notificationOccurred(.error) let title = NSLocalizedString("Could Not Follow Tag", comment: "Title of a prompt informing the user there was a probem unsubscribing from a tag in the reader.") let message = error?.localizedDescription let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addCancelActionWithTitle(NSLocalizedString("OK", comment: "Button title. An acknowledgement of the message displayed in a prompt.")) alert.presentFromRootViewController() }) } /// Scrolls the tableView so the specified tag is in view. /// /// - Paramters: /// - tag: The tag to scroll into view. /// func scrollToTag(_ tag: ReaderTagTopic) { guard let indexPath = viewModel.indexPathOfTag(tag) else { return } tableView.flashRowAtIndexPath(indexPath, scrollPosition: .middle, completion: { if !self.splitViewControllerIsHorizontallyCompact { self.tableView(self.tableView, didSelectRowAt: indexPath) } }) } // MARK: - TableView Delegate Methods override func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSectionsInMenu() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfItemsInSection(section) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return viewModel.titleForSection(section) } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { WPStyleGuide.configureTableViewSectionHeader(view) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let menuItem = viewModel.menuItemAtIndexPath(indexPath) if menuItem?.type == .addItem { let cell = tableView.dequeueReusableCell(withIdentifier: actionCellIdentifier)! configureActionCell(cell, atIndexPath: indexPath) return cell } let cell = tableView.dequeueReusableCell(withIdentifier: defaultCellIdentifier)! configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let menuItem = viewModel.menuItemAtIndexPath(indexPath) else { return } if menuItem.type == .addItem { tableView.deselectSelectedRowWithAnimation(true) showAddTag() return } restorableSelectedIndexPath = indexPath if let viewController = viewControllerForMenuItem(menuItem) { showDetailViewController(viewController, sender: self) } } fileprivate func viewControllerForMenuItem(_ menuItem: ReaderMenuItem) -> UIViewController? { if let topic = menuItem.topic { currentReaderStream = viewControllerForTopic(topic) return currentReaderStream } if menuItem.type == .search { currentReaderStream = nil return viewControllerForSearch() } return nil } func configureCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) { guard let menuItem = viewModel.menuItemAtIndexPath(indexPath) else { return } WPStyleGuide.configureTableViewCell(cell) cell.accessoryView = nil cell.accessoryType = (splitViewControllerIsHorizontallyCompact) ? .disclosureIndicator : .none cell.selectionStyle = .default cell.textLabel?.text = menuItem.title cell.imageView?.image = menuItem.icon } func configureActionCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) { guard let menuItem = viewModel.menuItemAtIndexPath(indexPath) else { return } WPStyleGuide.configureTableViewActionCell(cell) if cell.accessoryView == nil { let image = Gridicon.iconOfType(.plus) let imageView = UIImageView(image: image) imageView.tintColor = WPStyleGuide.wordPressBlue() cell.accessoryView = imageView } cell.selectionStyle = .default cell.imageView?.image = menuItem.icon cell.imageView?.tintColor = WPStyleGuide.wordPressBlue() cell.textLabel?.text = menuItem.title } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if !ReaderHelpers.isLoggedIn() { return false } guard let menuItem = viewModel.menuItemAtIndexPath(indexPath) else { return false } guard let topic = menuItem.topic else { return false } return ReaderHelpers.isTopicTag(topic) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard let menuItem = viewModel.menuItemAtIndexPath(indexPath) else { return } guard let topic = menuItem.topic as? ReaderTagTopic else { return } promptUnfollowTagTopic(topic) } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return NSLocalizedString("Remove", comment: "Label of the table view cell's delete button, when unfollowing tags.") } } extension ReaderMenuViewController: ReaderMenuViewModelDelegate { func menuDidReloadContent() { reloadTableViewPreservingSelection() } func menuSectionDidChangeContent(_ index: Int) { reloadTableViewPreservingSelection() } func reloadTableViewPreservingSelection() { let selectedIndexPath = restorableSelectedIndexPath tableView.reloadData() // Show the current selection if our split view isn't collapsed if !splitViewControllerIsHorizontallyCompact { tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .none) } } } extension ReaderMenuViewController: WPSplitViewControllerDetailProvider { func initialDetailViewControllerForSplitView(_ splitView: WPSplitViewController) -> UIViewController? { if restorableSelectedIndexPath == defaultIndexPath { let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext) if let topic = service.topicForFollowedSites() { return viewControllerForTopic(topic) } else { restorableSelectedIndexPath = IndexPath(row: 0, section: 0) if let item = viewModel.menuItemAtIndexPath(restorableSelectedIndexPath!) { return viewControllerForMenuItem(item) } } } return nil } }
gpl-2.0
0b8d8e0b04b3f45d14c5b699375f5d3f
34.80363
226
0.678527
5.812215
false
false
false
false
apple/swift-format
Sources/SwiftFormatCore/RuleState.swift
1
955
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// The enablement of a lint/format rule based on the presence or absence of comment directives in /// the source file. public enum RuleState { /// There is no explicit information in the source file about whether the rule should be enabled /// or disabled at the requested location, so the configuration default should be used. case `default` /// The rule is explicitly disabled at the requested location. case disabled }
apache-2.0
1b832fbbaa789d972a9128f64e2d1dfd
40.521739
98
0.62199
5.247253
false
false
false
false
LucaGobbo/MinuteAnimations
MinuteAnimations/Classes/KeyFrameAnimator.swift
1
3846
// // KeyFrameAnimator.swift // Pods // // Created by Luca Gobbo on 22-06-17. // // import Foundation import UIKit public extension UIView { public class KeyFrameAnimator { public typealias Completion = (Bool) -> Void public typealias SimpleCompletion = () -> Void //swiftlint:disable:next nesting private struct KeyFrameAnimation { let relativeStartTime: TimeInterval let relativeDuration: TimeInterval let animation: () -> Void init(relativeStartTime: TimeInterval, relativeDuration: TimeInterval, animation: @escaping () -> Void) { self.relativeStartTime = relativeStartTime self.relativeDuration = relativeDuration self.animation = animation } } private let duration: TimeInterval private let delay: TimeInterval private let options: UIViewKeyframeAnimationOptions private let animations: [KeyFrameAnimation] private let completion: Completion? public convenience init(duration: TimeInterval, delay: TimeInterval = 0, options: UIViewKeyframeAnimationOptions = []) { // we need to explicitly call the correct initializer otherwise it will recursivly call the same initializer self.init(duration: duration, delay: delay, options: options, animations: [], completion: nil) } private init(duration: TimeInterval, delay: TimeInterval = 0, options: UIViewKeyframeAnimationOptions = [], animations: [KeyFrameAnimation] = [], completion: Completion? = nil) { self.duration = duration self.delay = delay self.options = options self.animations = animations self.completion = completion } public func addAnimation(relativeStartTime: TimeInterval, relativeDuration: TimeInterval, animation: @escaping () -> Void) -> KeyFrameAnimator { let animation = KeyFrameAnimation(relativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animation: animation) return addAnimation(animation: animation) } public func completion(_ completion: SimpleCompletion?) -> KeyFrameAnimator { return KeyFrameAnimator(duration: duration, delay: delay, options: options, animations: animations, completion: { _ in completion?() }) } public func completion(_ completion: Completion?) -> KeyFrameAnimator { return KeyFrameAnimator(duration: duration, delay: delay, options: options, animations: animations, completion: completion) } public func animate() { UIView.animateKeyframes(withDuration: duration, delay: delay, options: options, animations: { self.animations.forEach { animation in UIView.addKeyframe(withRelativeStartTime: animation.relativeStartTime, relativeDuration: animation.relativeDuration, animations: animation.animation) } }, completion: completion) } private func addAnimation(animation: KeyFrameAnimation) -> KeyFrameAnimator { return KeyFrameAnimator(duration: duration, delay: delay, options: options, animations: animations + [animation], completion: completion) } } }
mit
3b0b1e870215dd052d1bc6e40e8e251a
33.963636
114
0.575923
6.551959
false
false
false
false
WildDogTeam/demo-ios-officemover
OfficeMover5000/PopoverMenuController.swift
1
2027
// // PopoverMenuController.swift // OfficeMover500 // // Created by Garin on 11/2/15. // Copyright (c) 2015 Wilddog. All rights reserved. // import UIKit @objc protocol PopoverMenuDelegate { func dismissPopover(animated: Bool) optional func addNewItem(type: String) func setBackgroundLocally(type: String) optional func setBackground(type: String) } class PopoverMenuController : UITableViewController { var delegate: PopoverMenuDelegate? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) view.backgroundColor = UIColor.clearColor() // iOS 8 } override func viewDidLoad() { super.viewDidLoad() preferredContentSize.height = 70 * CGFloat(numItems) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numItems } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: PopoverMenuItemCell! = tableView.dequeueReusableCellWithIdentifier("menuItemCell") as? PopoverMenuItemCell if cell == nil { cell = PopoverMenuItemCell(style: .Default, reuseIdentifier: "menuItemCell") } // Definitely exists now populateCell(cell, row: indexPath.row) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70 } // Dismiss the popover func dismissPopover(animated: Bool) { delegate?.dismissPopover(animated) // iOS 7 dismissViewControllerAnimated(animated, completion: nil) // iOS 8 } // Override this in subclass var numItems: Int { return 0 } // Override this in subclass func populateCell(cell: PopoverMenuItemCell, row: Int) {} }
mit
1e0d1d89b65e71fbde1138e7cfeee9d8
29.268657
124
0.674396
5.224227
false
false
false
false
lyft/SwiftLint
Tests/SwiftLintFrameworkTests/DiscouragedDirectInitRuleTests.swift
1
1456
import Foundation import SwiftLintFramework import XCTest class DiscouragedDirectInitRuleTests: XCTestCase { let baseDescription = DiscouragedDirectInitRule.description func testDiscouragedDirectInitWithDefaultConfiguration() { verifyRule(baseDescription) } func testDiscouragedDirectInitWithConfiguredSeverity() { verifyRule(baseDescription, ruleConfiguration: ["severity": "error"]) } func testDiscouragedDirectInitWithNewIncludedTypes() { let triggeringExamples = [ "let foo = ↓Foo()", "let bar = ↓Bar()" ] let nonTriggeringExamples = [ "let foo = Foo(arg: toto)", "let bar = Bar(arg: \"toto\")" ] let description = baseDescription .with(triggeringExamples: triggeringExamples) .with(nonTriggeringExamples: nonTriggeringExamples) verifyRule(description, ruleConfiguration: ["types": ["Foo", "Bar"]]) } func testDiscouragedDirectInitWithReplacedTypes() { let triggeringExamples = [ "let bundle = ↓Bundle()" ] let nonTriggeringExamples = [ "let device = UIDevice()" ] let description = baseDescription .with(triggeringExamples: triggeringExamples) .with(nonTriggeringExamples: nonTriggeringExamples) verifyRule(description, ruleConfiguration: ["types": ["Bundle"]]) } }
mit
5277488ca3c1f329139d4c87e79862a2
28.591837
77
0.641379
5.753968
false
true
false
false
phakphumi/Chula-Expo-iOS-Application
Chula Expo 2017/Chula Expo 2017/Modal_EventDetails/DocumentTableViewCell.swift
1
1752
// // DocumentTableViewCell.swift // Chula Expo 2017 // // Created by Pakpoom on 2/1/2560 BE. // Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved. // import UIKit class DocumentTableViewCell: UITableViewCell { @IBOutlet var bgView: UIView! @IBOutlet var documentView: UIView! @IBOutlet var descLabel: UILabel! @IBOutlet var iconImage: UIImageView! var pdfUrl: String! override func awakeFromNib() { super.awakeFromNib() // Initialization code documentView.layer.borderWidth = 2 documentView.layer.borderColor = UIColor(red: 0.694, green: 0.22, blue: 0.227, alpha: 1).cgColor documentView.layer.cornerRadius = 4 documentView.layer.masksToBounds = true let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DocumentTableViewCell.wasTap)) documentView.addGestureRecognizer(tapGestureRecognizer) documentView.isUserInteractionEnabled = true } func wasTap() { if pdfUrl == "" { let confirm = UIAlertController(title: "เกิดข้อผิดพลาด", message: "กิจกรรมนี้ไม่มีเอกสารประกอบ", preferredStyle: UIAlertControllerStyle.alert) confirm.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.destructive, handler: nil)) let parentVC = self.parentViewController! parentVC.present(confirm, animated: true, completion: nil) } else { UIApplication.shared.openURL(URL(string: pdfUrl)!) } } }
mit
fa3d14a61c1cf38bbdda1e0beedd822f
29.907407
154
0.630318
4.768571
false
false
false
false
khizkhiz/swift
stdlib/private/SwiftPrivate/SwiftPrivate.swift
2
2714
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// Convert the given numeric value to a hexadecimal string. public func asHex<T : Integer>(x: T) -> String { return "0x" + String(x.toIntMax(), radix: 16) } /// Convert the given sequence of numeric values to a string representing /// their hexadecimal values. public func asHex< S: Sequence where S.Iterator.Element : Integer >(x: S) -> String { return "[ " + x.lazy.map { asHex($0) }.joined(separator: ", ") + " ]" } /// Compute the prefix sum of `seq`. public func scan< S : Sequence, U >(seq: S, _ initial: U, _ combine: (U, S.Iterator.Element) -> U) -> [U] { var result: [U] = [] result.reserveCapacity(seq.underestimatedCount) var runningResult = initial for element in seq { runningResult = combine(runningResult, element) result.append(runningResult) } return result } public func randomShuffle<T>(a: [T]) -> [T] { var result = a for i in (1..<a.count).reversed() { // FIXME: 32 bits are not enough in general case! let j = Int(rand32(exclusiveUpperBound: UInt32(i + 1))) if i != j { swap(&result[i], &result[j]) } } return result } public func gather< C : Collection, IndicesSequence : Sequence where IndicesSequence.Iterator.Element == C.Index >( collection: C, _ indices: IndicesSequence ) -> [C.Iterator.Element] { return Array(indices.map { collection[$0] }) } public func scatter<T>(a: [T], _ idx: [Int]) -> [T] { var result = a for i in 0..<a.count { result[idx[i]] = a[i] } return result } public func withArrayOfCStrings<R>( args: [String], _ body: ([UnsafeMutablePointer<CChar>]) -> R ) -> R { let argsCounts = Array(args.map { $0.utf8.count + 1 }) let argsOffsets = [ 0 ] + scan(argsCounts, 0, +) let argsBufferSize = argsOffsets.last! var argsBuffer: [UInt8] = [] argsBuffer.reserveCapacity(argsBufferSize) for arg in args { argsBuffer.append(contentsOf: arg.utf8) argsBuffer.append(0) } return argsBuffer.withUnsafeBufferPointer { (argsBuffer) in let ptr = UnsafeMutablePointer<CChar>(argsBuffer.baseAddress) var cStrings = argsOffsets.map { ptr + $0 } cStrings[cStrings.count - 1] = nil return body(cStrings) } }
apache-2.0
d206cd5e26dab06a796a7c93725b90bb
26.979381
80
0.624539
3.667568
false
false
false
false
elationfoundation/Reporta-iOS
IWMF/Helper/CoreDataHelper.swift
1
2478
// // CoreDataHelper.swift // // import CoreData import UIKit class CoreDataHelper: NSObject{ let store: CoreDataStore! override init(){ self.store = Structures.Constant.appDelegate.cdstore super.init() NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSaveContext:", name: NSManagedObjectContextDidSaveNotification, object: nil) } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.store.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() lazy var backgroundContext: NSManagedObjectContext? = { let coordinator = self.store.persistentStoreCoordinator var backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) backgroundContext.persistentStoreCoordinator = coordinator return backgroundContext }() func saveContext (context: NSManagedObjectContext) { if context.hasChanges { do { try context.save() } catch _ as NSError { abort() } } } func saveContext () { self.saveContext( self.backgroundContext! ) } func contextDidSaveContext(notification: NSNotification) { let sender = notification.object as! NSManagedObjectContext if sender === self.managedObjectContext { self.backgroundContext!.performBlock { self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification) } } else if sender === self.backgroundContext { self.managedObjectContext.performBlock { self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification) } } else { self.backgroundContext!.performBlock { self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification) } self.managedObjectContext.performBlock { self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification) } } } }
gpl-3.0
d4af9f0402b88926ee352c954fd4f15a
32.04
160
0.658192
6.902507
false
false
false
false
landakram/kiwi
Kiwi/Controllers/AllPagesViewController.swift
1
6451
// // AllPagesViewController.swift // Kiwi // // Created by Mark Hudnall on 3/10/15. // Copyright (c) 2015 Mark Hudnall. All rights reserved. // import UIKit class AllPagesViewController: UITableViewController, UISearchResultsUpdating { var indexer: Indexer! var files: [String]! var filteredFiles: [String] = [] var selectedPermalink: String! var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() self.searchController = UISearchController() self.searchController.searchResultsUpdater = self self.searchController.dimsBackgroundDuringPresentation = false self.tableView.tableHeaderView = self.searchController.searchBar self.definesPresentationContext = true self.navigationItem.rightBarButtonItem = UIBarButtonItem( image: UIImage(named: "home"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(AllPagesViewController.navigateToHomePage) ) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.searchController.isActive { return self.filteredFiles.count } else { return self.files.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell var files = self.files if self.searchController.isActive { files = self.filteredFiles cell = self.tableView.dequeueReusableCell(withIdentifier: "pageCell")! } else { cell = self.tableView.dequeueReusableCell(withIdentifier: "pageCell", for: indexPath) } let fileName = (files?[(indexPath as NSIndexPath).row])?.stringByDeletingPathExtension if let titleLabel = cell.viewWithTag(100) as? UILabel { titleLabel.text = Page.permalinkToName(permalink: fileName!) } if let detailLabel = cell.viewWithTag(101) as? UILabel { detailLabel.text = nil; } if let page = self.indexer.get(permalink: fileName!) { let characterSet = CharacterSet.whitespacesAndNewlines let components = page.rawContent.components(separatedBy: characterSet) let length = min(components.count, 30) let firstWords = components[0..<length].joined(separator: " ") if let detailLabel = cell.viewWithTag(101) as? UILabel { detailLabel.text = firstWords; } } // Configure the cell... return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.selectedPermalink = self.files[(indexPath as NSIndexPath).row] } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 105.0; } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 NO if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation @objc func navigateToHomePage() { self.performSegue(withIdentifier: "NavigateToSelectedPage", sender: self) } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "NavigateToSelectedPage" { self.searchController.searchBar.resignFirstResponder() if let cell = sender as? UITableViewCell { if let textLabel = cell.viewWithTag(100) as? UILabel { self.selectedPermalink = Page.nameToPermalink(name: textLabel.text!) } } else { self.selectedPermalink = "home" } } // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } // MARK: - Search func searchPages(_ searchText: String) { if searchText.characters.count >= 2 { let characterSet = CharacterSet.whitespacesAndNewlines let components = searchText.components(separatedBy: characterSet).map( { (word) in word + "*" }) let searchTerms = components.joined(separator: " ") self.filteredFiles.removeAll(keepingCapacity: true) let matches = self.indexer.find(snippet: searchTerms) self.filteredFiles += matches } } func updateSearchResults(for searchController: UISearchController) { if let str = searchController.searchBar.text { self.searchPages(str) } self.tableView.reloadData() } }
mit
bc9472d60d8995480e2613b0c58ef1f0
35.446328
157
0.643621
5.389307
false
false
false
false
nifty-swift/Nifty
Sources/Nifty.swift
2
2536
/************************************************************************************************** * Nifty.swift * * This file provides a class for namespacing options and constants. * * Author: Philip Erickson * Creation Date: 1 Jan 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2017 Philip Erickson **************************************************************************************************/ public class Nifty { /// Contains all options used throughout Nifty. /// /// Options are name for the function that uses them, and are either enums, or structs wrapping /// enums to provide another level of hierarchy. /// /// Options that don't clearly belong to a particular source file may be defined here. Or, if there /// is a clear correspondence, and extension to this struct may be made in that file. public class Options { /// /// - nearlin: use linear interpolation where possible, elsewhere use nearest neighbor public enum EstimationMethod { case gaussproc case linreg case linterp case nearest case nearlin case next case previous case spline } } /// Contains constant definitions used throughout Nifty. public class Constants { /* // TODO: determine better way to do this, e.g. static inside class so Nifty.Pi? /// Default tolerance used for comparing decimal values. public let DefaultDecimalTolerance = 1e-12 /// Special double values public let NaN = Double.nan public let Inf = Double.infinity /// Pi public let Pi = 3.141592653589793 /// Euler's number public let E = 2.718281828459046 */ public static let e = 2.718281828459046 public static let phi = 1.618033988749895 public static let pi = 3.141592653589793 } }
apache-2.0
9590a6684d80a9f3e5e48e209c8f400c
32.813333
104
0.587145
5.112903
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Tests/EurofurenceModelAdapterTests/Image Repository/PersistentImageRepositoryTests.swift
1
1757
import EurofurenceModel import TestUtilities import XCTest class PersistentImageRepositoryTests: XCTestCase { func testSavingImageThenLoadingAgain() { let identifier = String.random let imageData = Data.random var repository = PersistentImageRepository() let expected = ImageEntity(identifier: identifier, pngImageData: imageData) repository.save(expected) repository = PersistentImageRepository() let actual = repository.loadImage(identifier: identifier) XCTAssertEqual(expected, actual) } func testSavingImageIndicatesRepositoryContainsImage() { let identifier = String.random let imageData = Data.random let repository = PersistentImageRepository() let expected = ImageEntity(identifier: identifier, pngImageData: imageData) repository.save(expected) XCTAssertTrue(repository.containsImage(identifier: identifier)) } func testNotContainImageThatHasNotBeenSaved() { let repository = PersistentImageRepository() XCTAssertFalse(repository.containsImage(identifier: .random)) } func testDeletingImageDoesNotRestoreItLater() { let identifier = String.random let imageData = Data.random var repository = PersistentImageRepository() let entity = ImageEntity(identifier: identifier, pngImageData: imageData) repository.save(entity) repository = PersistentImageRepository() repository.deleteEntity(identifier: entity.identifier) repository = PersistentImageRepository() XCTAssertNil(repository.loadImage(identifier: entity.identifier), "Deleted images should not be restored by repository later") } }
mit
59e7cdef1fc65149dd74f5f8ae6f10cb
35.604167
83
0.714855
5.876254
false
true
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/CollectionViewSelfSizing.swift
1
2893
// // CollectionViewSelfSizing.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/7/19. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class CollectionViewSelfSizing: UIViewController { fileprivate lazy var items: [String] = [] private lazy var collectionView: UICollectionView = { var rect = self.view.frame let layout = UICollectionViewFlowLayout() layout.estimatedItemSize = CGSize(width: 1, height: 1) layout.minimumLineSpacing = 16 layout.minimumInteritemSpacing = 16 let collectionView = UICollectionView(frame: rect, collectionViewLayout: layout) collectionView.dataSource = self collectionView.backgroundColor = .white collectionView.register(MyCell.self, forCellWithReuseIdentifier: "cell") return collectionView }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue for _ in 0 ..< 10 { items.append("I'm trying to get self sizing UICollectionViewCells working with Auto Layout, but I can't seem to get the cells to size themselves to the content. I'm having trouble understanding how the cell's size is updated from the contents of what's inside the cell's contentView.") } view.addSubview(collectionView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension CollectionViewSelfSizing: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) (cell as? MyCell)?.text = items[indexPath.row] return cell } } class MyCell: UICollectionViewCell { let textLabel = UILabel() var text: String? { didSet { textLabel.text = text } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(white: 0.8, alpha: 1) contentView.snp.makeConstraints { (make) in make.width.equalTo(UIScreen.main.bounds.width - 32) } contentView.addSubview(textLabel) textLabel.numberOfLines = 0 textLabel.backgroundColor = UIColor(white: 0.9, alpha: 1) textLabel.snp.makeConstraints { (make) in make.left.top.equalTo(8) make.right.bottom.equalTo(-8) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
68d679db635991f4d4bbfa405dd78460
31.337079
297
0.656011
5.111901
false
false
false
false
ruter/Strap-in-Swift
StormViewer/StormViewer/MasterViewController.swift
1
2517
// // MasterViewController.swift // StormViewer // // Created by Ruter on 16/4/12. // Copyright © 2016年 Ruter. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "PicList" let fm = NSFileManager.defaultManager() let path = NSBundle.mainBundle().resourcePath! let items = try! fm.contentsOfDirectoryAtPath(path) for item in items { if item.hasPrefix("nssl") { objects.append(item) } } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true self.tableView.deselectRowAtIndexPath(indexPath, animated: false) } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] cell.textLabel!.text = object return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } }
apache-2.0
5f210f966ab01ae5f6af7c6ef72e4166
28.928571
132
0.709626
5.292632
false
false
false
false
aaronraimist/firefox-ios
Client/Frontend/Settings/AppSettingsOptions.swift
1
32506
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Sign In to Firefox", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var accessibilityIdentifier: String? { return "SignInToFirefox" } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self viewController.url = settings.profile.accountConfiguration.signInURL navigationController?.pushViewController(viewController, animated: true) } } // Sync setting for disconnecting a Firefox Account. Shown when we have an account. class DisconnectSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .None } override var textAlignment: NSTextAlignment { return .Center } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed]) } override var accessibilityIdentifier: String? { return "LogOut" } override func onClick(navigationController: UINavigationController?) { let alertController = UIAlertController( title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"), message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"), preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .Cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in self.settings.profile.removeAccount() self.settings.settings = self.settings.generateSettings() self.settings.SELfirefoxAccountDidChange() }) navigationController?.presentViewController(alertController, animated: true, completion: nil) } } class SyncNowSetting: WithAccountSetting { static let NotificationUserInitiatedSyncManually = "NotificationUserInitiatedSyncManually" private lazy var timestampFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() private var syncNowTitle: NSAttributedString { return NSAttributedString( string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [ NSForegroundColorAttributeName: self.enabled ? UIColor.blackColor() : UIColor.grayColor(), NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFont ] ) } private let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFontWeightRegular)]) override var accessoryType: UITableViewCellAccessoryType { return .None } override var style: UITableViewCellStyle { return .Value1 } override var title: NSAttributedString? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncNowTitle } switch syncStatus { case .Bad(let message): guard let message = message else { return syncNowTitle } return NSAttributedString(string: message, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowErrorTextColor, NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .Stale(let message): return NSAttributedString(string: message, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowWarningTextColor, NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .InProgress: return syncingTitle default: return syncNowTitle } } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let formattedLabel = timestampFormatter.stringFromDate(NSDate.fromTimestamp(timestamp)) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12, weight: UIFontWeightRegular)] let range = NSMakeRange(0, attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override var enabled: Bool { return profile.hasSyncableAccount() } private lazy var troubleshootButton: UIButton = { let troubleshootButton = UIButton(type: UIButtonType.RoundedRect) troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, forState: .Normal) troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), forControlEvents: .TouchUpInside) troubleshootButton.tintColor = UIConstants.TableViewRowActionAccessoryColor troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont troubleshootButton.sizeToFit() return troubleshootButton }() private lazy var warningIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "AmberCaution")) imageView.sizeToFit() return imageView }() private lazy var errorIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "RedCaution")) imageView.sizeToFit() return imageView }() private let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios") @objc private func troubleshoot() { let viewController = SettingsContentViewController() viewController.url = syncSUMOURL settings.navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .ByWordWrapping if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .Bad(let message): if let _ = message { // add the red warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(errorIcon, toCell: cell) } else { cell.detailTextLabel?.attributedText = status cell.accessoryView = nil } case .Stale(_): // add the amber warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(warningIcon, toCell: cell) case .Good: cell.detailTextLabel?.attributedText = status fallthrough default: cell.accessoryView = nil } } else { cell.accessoryView = nil } cell.accessoryType = accessoryType cell.userInteractionEnabled = !profile.syncManager.isSyncing } private func addIcon(image: UIImageView, toCell cell: UITableViewCell) { cell.contentView.addSubview(image) cell.textLabel?.snp_updateConstraints { make in make.leading.equalTo(image.snp_trailing).offset(5) make.trailing.lessThanOrEqualTo(cell.contentView) make.centerY.equalTo(cell.contentView) } image.snp_makeConstraints { make in make.leading.equalTo(cell.contentView).offset(17) make.top.equalTo(cell.textLabel!).offset(2) } } override func onClick(navigationController: UINavigationController?) { NSNotificationCenter.defaultCenter().postNotificationName(SyncNowSetting.NotificationUserInitiatedSyncManually, object: nil) profile.syncManager.syncEverything() } } // Sync setting that shows the current Firefox Account status. class AccountStatusSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: // We link to the resend verification email page. return .DisclosureIndicator case .NeedsPassword: // We link to the re-enter password page. return .DisclosureIndicator case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return .None } } return .DisclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { switch account.actionNeeded { case .None: return nil case .NeedsVerification: return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) case .NeedsPassword: let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res case .NeedsUpgrade: let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } } return nil } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsPassword: let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return } } navigationController?.pushViewController(viewController, animated: true) } } // For great debugging! class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let fileManager = NSFileManager.defaultManager() do { let files = try fileManager.contentsOfDirectoryAtPath(documentsPath) for file in files { if file.startsWith("browser.") || file.startsWith("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.startsWith("browser.") || file.startsWith("logins.") } } catch { print("Couldn't export browser data: \(error).") } } } // Show the current version of Firefox class VersionSetting : Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .None } override func onClick(navigationController: UINavigationController?) { if AppConstants.BuildChannel != .Aurora { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } } } // Opens the the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class SendAnonymousUsageDataSetting: BoolSetting { init(prefs: Prefs, delegate: SettingsDelegate?) { super.init( prefs: prefs, prefKey: "settings.sendUsageData", defaultValue: true, attributedTitleText: NSAttributedString(string: NSLocalizedString("Send Anonymous Usage Data", tableName: "SendAnonymousUsageData", comment: "See http://bit.ly/1SmEXU1")), attributedStatusText: NSAttributedString(string: NSLocalizedString("More Info…", tableName: "SendAnonymousUsageData", comment: "See http://bit.ly/1SmEXU1"), attributes: [NSForegroundColorAttributeName: UIConstants.HighlightBlue]), settingDidChange: { AdjustIntegration.setEnabled($0) } ) } override var url: NSURL? { return SupportUtils.URLForTopic("adjust") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the the SUMO page in a new tab class OpenSupportPageSetting: Setting { init(delegate: SettingsDelegate?) { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), delegate: delegate) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true) { if let url = NSURL(string: "https://support.mozilla.org/products/ios") { self.delegate?.settingsOpenURLInNewTab(url) } } } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var style: UITableViewCellStyle { return .Value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! weak var navigationController: UINavigationController? weak var settings: AppSettingsTableViewController? override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.tabManager = settings.tabManager self.navigationController = settings.navigationController self.settings = settings as? AppSettingsTableViewController let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.") super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), delegate: delegate) } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.authenticationInfo() else { settings?.navigateToLoginsList() return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.loginsTouchReason, success: { self.settings?.navigateToLoginsList() }, cancel: { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRowAtIndexPath(selectedRow, animated: true) } }, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self.settings) }) } else { settings?.navigateToLoginsList() } } } class TouchIDPasscodeSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var accessibilityIdentifier: String? { return "TouchIDPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.profile = settings.profile self.tabManager = settings.tabManager let title: String if LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) { title = AuthenticationStrings.touchIDPasscodeSetting } else { title = AuthenticationStrings.passcode } super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), delegate: delegate) } override func onClick(navigationController: UINavigationController?) { let viewController = AuthenticationSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = Strings.SettingsClearPrivateDataSectionName super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChinaSyncServiceSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .None } var prefs: Prefs { return settings.profile.prefs } let prefKey = "useChinaSyncService" override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var status: NSAttributedString? { return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(ChinaSyncServiceSetting.switchValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged) control.on = prefs.boolForKey(prefKey) ?? true cell.accessoryView = control cell.selectionStyle = .None } @objc func switchValueChanged(toggle: UISwitch) { prefs.setObject(toggle.on, forKey: prefKey) } } class HomePageSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var accessibilityIdentifier: String? { return "HomePageSetting" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsHomePageSectionName, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = HomePageSettingsViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class NewTabPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var accessibilityIdentifier: String? { return "NewTabPage.Setting" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = NewTabChoiceViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } }
mpl-2.0
f7a7fb10be8a9019cf1de2f5d9775188
42.227696
299
0.699637
6.001849
false
false
false
false
lizhihui0215/PCCWFoundationSwift
Source/PFSTableViewController.swift
1
2620
// // PFSTableViewController.swift // IBLNetAssistant // // Created by 李智慧 on 02/07/2017. // Copyright © 2017 李智慧. All rights reserved. // import UIKit import RxCocoa import RxSwift import MJRefresh public protocol RMTableViewRefresh: class { func headerRefreshingFor(tableView: UITableView) func footerRefreshingFor(tableView: UITableView) } extension UITableView { public func headerRefresh(enable: Bool, target: RMTableViewRefresh) { if enable { weak var x = target self.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in if let strongSelf = self, let strongTarget = x { strongTarget.headerRefreshingFor(tableView: strongSelf) } }) }else{ self.mj_header = nil } } public func footerRefresh(enable: Bool, target: RMTableViewRefresh) { if enable { weak var x = target self.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {[weak self] in if let strongSelf = self, let strongTarget = x { strongTarget.footerRefreshingFor(tableView: strongSelf) } }) }else{ self.mj_footer = nil } } } open class PFSTableViewController: PFSViewController,RMTableViewRefresh { @IBOutlet public var tableViews: [UITableView]! public var tableView: UITableView { return tableViews[0] } open override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.emptyFooterView() } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } open func emptyFooterView() { for tableView in self.tableViews { tableView.tableFooterView = UIView() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 40 } } open func footerRefreshingFor(tableView: UITableView) {} open func headerRefreshingFor(tableView: UITableView) {} /* // 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
4079963a002c2a6bd04db633aac87846
27.336957
106
0.627925
5.152174
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Browser/OpenWithSettingsViewController.swift
3
4783
/* 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 class OpenWithSettingsViewController: UITableViewController { typealias MailtoProviderEntry = (name: String, scheme: String, enabled: Bool) var mailProviderSource = [MailtoProviderEntry]() fileprivate let prefs: Prefs fileprivate var currentChoice: String = "mailto" fileprivate let BasicCheckmarkCell = "BasicCheckmarkCell" init(prefs: Prefs) { self.prefs = prefs super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsOpenWithSectionName tableView.accessibilityIdentifier = "OpenWithPage.Setting.Options" tableView.register(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell) tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor let headerFooterFrame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.frame.width, height: UIConstants.TableViewHeaderFooterHeight)) let headerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame) headerView.titleLabel.text = Strings.SettingsOpenWithPageTitle.uppercased() headerView.showTopBorder = false headerView.showBottomBorder = true let footerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame) footerView.showTopBorder = true footerView.showBottomBorder = false tableView.tableHeaderView = headerView tableView.tableFooterView = footerView NotificationCenter.default.addObserver(self, selector: #selector(OpenWithSettingsViewController.appDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) appDidBecomeActive() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.prefs.setString(currentChoice, forKey: PrefsKeys.KeyMailToOption) } func appDidBecomeActive() { reloadMailProviderSource() updateCurrentChoice() tableView.reloadData() } func updateCurrentChoice() { var previousChoiceAvailable: Bool = false if let prefMailtoScheme = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { mailProviderSource.forEach({ (name, scheme, enabled) in if scheme == prefMailtoScheme { previousChoiceAvailable = enabled } }) } if !previousChoiceAvailable { self.prefs.setString(mailProviderSource[0].scheme, forKey: PrefsKeys.KeyMailToOption) } if let updatedMailToClient = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { self.currentChoice = updatedMailToClient } } func reloadMailProviderSource() { if let path = Bundle.main.path(forResource: "MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) { mailProviderSource = dictRoot.map { dict in let nsDict = dict as! NSDictionary return (name: nsDict["name"] as! String, scheme: nsDict["scheme"] as! String, enabled: canOpenMailScheme(nsDict["scheme"] as! String)) } } } func canOpenMailScheme(_ scheme: String) -> Bool { if let url = URL(string: scheme) { return UIApplication.shared.canOpenURL(url) } return false } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: BasicCheckmarkCell, for: indexPath) let option = mailProviderSource[indexPath.row] cell.textLabel?.attributedText = NSAttributedString.tableRowTitle(option.name, enabled: option.enabled) cell.accessoryType = (currentChoice == option.scheme && option.enabled) ? .checkmark : .none cell.isUserInteractionEnabled = option.enabled return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mailProviderSource.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.currentChoice = mailProviderSource[indexPath.row].scheme tableView.reloadData() } }
mpl-2.0
22cc8a76e995eb36121b64ee58b6590b
37.886179
193
0.689107
5.660355
false
false
false
false
quickthyme/PUTcat
PUTcat/Application/Data/Parameter/DataStore/PCParameterDataStoreMock.swift
1
1271
import Foundation class PCParameterDataStoreMock : PCParameterDataStore { private static let StorageResource = "parameter-list" private static let StorageKey = "parameters" static func fetch(transactionID: String, asCopy: Bool) -> Composed.Action<Any, PCList<PCParameter>> { return Composed.Action<Any, PCList<PCParameter>> { _, completion in let path = Bundle(for: self).path(forResource: StorageResource, ofType: "json") guard let dict = xJSON.parse(file: path) as? [String:Any], let items = dict[StorageKey] as? [[String:Any]] else { return completion( .failure(PCError(code: 404, text: "Error retrieving \(StorageKey)")) ) } let list = PCList<PCParameter>(fromLocal: items) completion( .success( (asCopy) ? list.copy() : list ) ) } } static func store(transactionID: String) -> Composed.Action<PCList<PCParameter>, PCList<PCParameter>> { return Composed.Action<PCList<PCParameter>, PCList<PCParameter>> { list, completion in completion(.success(list)) } } }
apache-2.0
6d1f3571787c9df78b6850afb6863fa6
36.382353
107
0.570417
4.851145
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Me/Drafts/YYCache+Draft.swift
1
953
// // YYCache+Draft.swift // HiPDA // // Created by leizh007 on 2017/7/7. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import YYCache import Argo import HandyJSON extension YYCache { enum Constants { static let draftKey = "draft" } func drafts() -> [Draft] { guard let draftsString = object(forKey: Constants.draftKey) as? String, let draftsData = draftsString.data(using: .utf8), let data = try? JSONSerialization.jsonObject(with: draftsData, options: []), let arr = data as? NSArray else { return [] } return arr.flatMap { return try? Draft.decode(JSON($0)).dematerialize() } } func setDrafts(_ drafts: [Draft]) { let draftsString = JSONSerializer.serializeToJSON(object: drafts) ?? "" setObject(draftsString as NSString, forKey: Constants.draftKey) } }
mit
158e3b717af0b7e80a105178e8033f20
25.388889
88
0.603158
4.148472
false
false
false
false
4np/UitzendingGemist
UitzendingGemist/String+i18n.swift
1
4922
// // String+i18n.swift // UitzendingGemist // // Created by Jeroen Wesbeek on 10/04/2017. // Copyright © 2017 Jeroen Wesbeek. All rights reserved. // import Foundation extension String { // Configuration static let closedCaptioningHelpTitle = NSLocalizedString("Ondertiteling", comment: "Closed captioning") static let closedCaptioningHelpText = NSLocalizedString("De meeste programma's hebben ondertitels beschikbaar voor doven en slechthorenden. Wanneer deze optie is ingeschakeld zullen -wanneer beschikbaar- bekeken afleveringen worden ondertiteld.", comment: "Most programs have closed captioning available for the deaf and hearing impaired. Enabling this setting will -when available- display closed captioning for when watching an episode.") static let secureTransportHelpTitle = NSLocalizedString("Beveiligde verbinding", comment: "Secure transport") static let secureTransportHelpText = NSLocalizedString("Indien ingeschakeld zullen alléén beveiligde verbindingen worden gebruikt. Wanneer u zich in het buitenland bevindt en gebruik maakt van 'unlocator' dan dient u deze optie uit te schakelen.", comment: "When enabled only secure connections will be used. If you are abroad and make use of the 'unlocator' service, you should disable this option for the service to work properly.") static let unknownText = NSLocalizedString("Onbekend", comment: "Unkown") static let unknownEpisodeName = NSLocalizedString("Naamloze aflevering", comment: "Unkown episode name") static let unknownProgramName = NSLocalizedString("Naamloos programma", comment: "Unkown program name") static let genreText = NSLocalizedString("Genre", comment: "Genre") static let broadcasterText = NSLocalizedString("Omroep", comment: "Broadcaster") static let warningEpisodeUnavailable = NSLocalizedString("Deze aflevering is momenteel niet beschikbaar", comment: "This episode is currently not available") static let warningEpisodeUnavailableFromLocation = NSLocalizedString("Deze aflevering is niet beschikbaar op uw locatie", comment: "This episode is not available on your location") static let warningEpisodeUnavailableFromCountry = NSLocalizedString("Deze aflevering is niet beschikbaar vanuit %@", comment: "This episode is not available from [some country]") static let playText = NSLocalizedString("Speel", comment: "Play") static let playUnavailableText = NSLocalizedString("Niet beschikbaar", comment: "Not available") static let toProgramText = NSLocalizedString("Naar Programma", comment: "To Program") static let favoriteText = NSLocalizedString("Favoriet", comment: "Favorite") static let continueWatchingTitleText = NSLocalizedString("Verder kijken", comment: "Continue watching") static let continueWatchingMessageText = NSLocalizedString("U heeft deze aflevering al deels bekeken. Wilt u verder kijken vanaf het punt waar u bent gebleven of wilt u opnieuw beginnen?", comment: "Ask user to continue watching or to restart") static let coninueWatchingFromText = NSLocalizedString("Verder kijken vanaf %@", comment: "Continue watching from hh:min:ss") static let watchFromStartText = NSLocalizedString("Bij het begin beginnen", comment: "Start watching from the beginning") static let cancelText = NSLocalizedString("Annuleren", comment: "Cancel") static let waitText = NSLocalizedString("Een ogenblik geduld alstublieft...", comment: "Please wait text") static let updateAvailableTitle = NSLocalizedString("Nieuwere versie beschikbaar", comment: "A newer version is available") static let updateAvailableText = NSLocalizedString("Uitzending Gemist versie '%@' is beschikbaar op %@ . Momenteel maakt u gebruik van Uitzending Gemist versie '%@'.", comment: "A newer version is available for download") static let okayButtonText = NSLocalizedString("OK", comment: "OK Button Text") static let commercials = NSLocalizedString("Reclame of geen uitzending", comment: "Commercial break or no broadcast") static let currentBroadcast = NSLocalizedString("Nu: %@", comment: "Current broadcast") static let upcomingBroadcast = NSLocalizedString("Straks: %@", comment: "Upcoming broadcast (without time)") static let upcomingBroadcastWithTime = NSLocalizedString("%@: %@", comment: "Upcoming broadcast (with time)") static let markAsWatchedText = NSLocalizedString("Markeer als gezien", comment: "Mark episode as watched") static let markAllAsWatchedText = NSLocalizedString("Markeer alles als gezien", comment: "Mark all episodes as watched") static let markAsUnwatchedText = NSLocalizedString("Markeer als ongezien", comment: "Mark episode as unwatched") static let markAllAsUnwatchedText = NSLocalizedString("Markeer alles als ongezien", comment: "Mark all episodes as unwatched") }
apache-2.0
1edc47585223feda976ac2f5cb060b06
86.839286
444
0.76296
4.588619
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Views/GroupInvitationListView.swift
1
2542
// // GroupInvitationListView.swift // Habitica // // Created by Phillip Thelen on 22.06.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import PinLayout import ReactiveSwift class GroupInvitationListView: UIView { private var invitationViews = [GroupInvitationView]() private let socialRepository = SocialRepository() private var disposable = CompositeDisposable() func set(invitations: [GroupInvitationProtocol]?) { if !disposable.isDisposed { disposable.dispose() } disposable = CompositeDisposable() invitationViews.forEach { (view) in view.removeFromSuperview() } invitationViews.removeAll() for invitation in invitations ?? [] { let view = GroupInvitationView() view.set(invitation: invitation) view.responseAction = {[weak self] didAccept in guard let groupID = invitation.id else { return } if didAccept { self?.socialRepository.joinGroup(groupID: groupID).observeCompleted {} } else { self?.socialRepository.rejectGroupInvitation(groupID: groupID).observeCompleted {} } } if let inviterID = invitation.inviterID { DispatchQueue.main.async {[weak self] in self?.disposable.add(self?.socialRepository.getMember(userID: inviterID).skipNil().on(value: { member in view.set(inviter: member) }).start()) } } addSubview(view) invitationViews.append(view) } invitationViews.dropFirst().forEach { (view) in view.showSeparator = true } setNeedsLayout() invalidateIntrinsicContentSize() } override func layoutSubviews() { super.layoutSubviews() layout() } private func layout() { var topEdge = edge.top for view in invitationViews { view.pin.top(to: topEdge).width(frame.size.width).height(70) topEdge = view.edge.bottom } } override var intrinsicContentSize: CGSize { layout() let height = (invitationViews.last?.frame.origin.y ?? 0) + (invitationViews.last?.frame.size.height ?? 0) return CGSize(width: frame.size.width, height: height) } }
gpl-3.0
042cf57068546edcf62b9bc3d8be4cf6
31.164557
124
0.578512
5.26087
false
false
false
false
jlhonora/androidtool-mac
AndroidTool/Device.swift
1
4006
// // Device.swift // AndroidTool // // Created by Morten Just Petersen on 4/22/15. // Copyright (c) 2015 Morten Just Petersen. All rights reserved. // import Cocoa import AVFoundation protocol DeviceDelegate{ // } enum DeviceType:String { case Phone="Phone", Watch="Watch", Tv="Tv", Auto="Auto" } enum DeviceOS { case Ios, Android } class Device: NSObject { var model : String? // Nexus 6 var name : String? // Shamu var manufacturer : String? // Motorola var type: DeviceType? var brand: String? // google var serial: String? var properties: [String:String]? var firstBoot : NSTimeInterval? var firstBootString : NSString? var adbIdentifier : String? var isEmulator : Bool = false var displayHeight : Int? var resolution : (width:Double, height:Double)? var deviceOS : DeviceOS! var uuid : String! var avDevice : AVCaptureDevice! // for iOS only convenience init(avDevice:AVCaptureDevice) { self.init() deviceOS = DeviceOS.Ios firstBoot = hashFromString(avDevice.uniqueID) brand = "Apple" name = avDevice.localizedName uuid = avDevice.uniqueID model = name self.avDevice = avDevice } convenience init(properties:[String:String], adbIdentifier:String) { self.init() deviceOS = .Android self.adbIdentifier = adbIdentifier.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) model = properties["ro.product.model"] name = properties["ro.product.name"] manufacturer = properties["ro.product.manufacturer"] brand = properties["ro.product.brand"] firstBootString = properties["ro.runtime.firstboot"] firstBoot = firstBootString?.doubleValue if let deviceSerial = properties["ro.serialno"]{ serial = deviceSerial } else { isEmulator = true serial = adbIdentifier } if let characteristics = properties["ro.build.characteristics"] { if characteristics.rangeOfString("watch") != nil { type = DeviceType.Watch } else { type = DeviceType.Phone } } ShellTasker(scriptFile: "getResolutionForSerial").run(arguments: ["\(self.adbIdentifier!)"], isUserScript: false) { (output) -> Void in let res = output as! String if res.rangeOfString("Physical size:") != nil { self.resolution = self.getResolutionFromString(output as! String) } else { println("Awkward. No size found. What I did find was \(res)") } } } func hashFromString(s:String) -> Double { return Double(abs((s as NSString).hash)) } func readableIdentifier() -> String { if let modelString = model { return modelString } else if let nameString = name { return nameString } else if let manufacturerString = manufacturer { return manufacturerString } else if let serialString = serial { return serialString } else { return "Mobile device" } } func getResolutionFromString(string:String) -> (width:Double, height:Double) { let re = NSRegularExpression(pattern: "Physical size: (.*)x(.*)", options: nil, error: nil)! let matches = re.matchesInString(string, options: nil, range: NSRange(location: 0, length: count(string.utf16))) let result = matches[0] as! NSTextCheckingResult let width:NSString = (string as NSString).substringWithRange(result.rangeAtIndex(1)) let height:NSString = (string as NSString).substringWithRange(result.rangeAtIndex(2)) let res = (width:width.doubleValue, height:height.doubleValue) return res } }
apache-2.0
e9263d927b2e3d96d4a866ee4492dc67
31.306452
143
0.604843
4.791866
false
false
false
false
eBardX/XestiMonitors
Tests/CoreLocation/StandardLocationMonitorTests.swift
1
13856
// // StandardLocationMonitorTests.swift // XestiMonitorsTests // // Created by J. G. Pusey on 2018-03-22. // // © 2018 J. G. Pusey (see LICENSE.md) // import CoreLocation import XCTest @testable import XestiMonitors // swiftlint:disable type_body_length internal class StandardLocationMonitorTests: XCTestCase { let locationManager = MockLocationManager() override func setUp() { super.setUp() LocationManagerInjector.inject = { self.locationManager } } #if os(iOS) || os(watchOS) func testActivityType_get() { if #available(watchOS 4.0, *) { let expectedActivityType: CLActivityType = .automotiveNavigation let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.activityType = expectedActivityType XCTAssertEqual(monitor.activityType, expectedActivityType) } } #endif #if os(iOS) || os(watchOS) func testActivityType_set() { if #available(watchOS 4.0, *) { let expectedActivityType: CLActivityType = .fitness let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.activityType = expectedActivityType XCTAssertEqual(locationManager.activityType, expectedActivityType) } } #endif #if os(iOS) func testAllowDeferredUpdates() { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.startMonitoring() monitor.allowDeferredUpdates(untilTraveled: 500, timeout: 10) XCTAssertTrue(locationManager.isLocationUpdatesDeferred) } #endif #if os(iOS) || os(watchOS) func testAllowsBackgroundLocationUpdates_get() { if #available(watchOS 4.0, *) { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.allowsBackgroundLocationUpdates = true XCTAssertTrue(monitor.allowsBackgroundLocationUpdates) } } #endif #if os(iOS) || os(watchOS) func testAllowsBackgroundLocationUpdates_set() { if #available(watchOS 4.0, *) { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.allowsBackgroundLocationUpdates = true XCTAssertTrue(locationManager.allowsBackgroundLocationUpdates) } } #endif #if os(iOS) || os(macOS) func testCanDeferUpdates_false() { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.updateStandardLocation(canDeferUpdates: false) XCTAssertFalse(monitor.canDeferUpdates) } #endif #if os(iOS) || os(macOS) func testCanDeferUpdates_true() { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.updateStandardLocation(canDeferUpdates: true) XCTAssertTrue(monitor.canDeferUpdates) } #endif func testDesiredAccuracy_get() { let expectedDesiredAccuracy: CLLocationAccuracy = 123 let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.desiredAccuracy = expectedDesiredAccuracy XCTAssertEqual(monitor.desiredAccuracy, expectedDesiredAccuracy) } func testDesiredAccuracy_set() { let expectedDesiredAccuracy: CLLocationAccuracy = 321 let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.desiredAccuracy = expectedDesiredAccuracy XCTAssertEqual(locationManager.desiredAccuracy, expectedDesiredAccuracy) } #if os(iOS) func testDisallowDeferredUpdates() { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.startMonitoring() monitor.allowDeferredUpdates(untilTraveled: 0, timeout: 0) monitor.disallowDeferredUpdates() XCTAssertFalse(locationManager.isLocationUpdatesDeferred) } #endif func testDistanceFilter_get() { let expectedDistanceFilter: CLLocationDistance = 2_001 let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.distanceFilter = expectedDistanceFilter XCTAssertEqual(monitor.distanceFilter, expectedDistanceFilter) } func testDistanceFilter_set() { let expectedDistanceFilter: CLLocationDistance = 1_002 let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.distanceFilter = expectedDistanceFilter XCTAssertEqual(locationManager.distanceFilter, expectedDistanceFilter) } func testLocation_nil() { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.updateStandardLocation(forceLocation: nil) XCTAssertNil(monitor.location) } func testLocation_nonnil() { let expectedLocation = CLLocation() let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.updateStandardLocation(forceLocation: expectedLocation) if let location = monitor.location { XCTAssertEqual(location, expectedLocation) } else { XCTFail("Unexpected location") } } #if os(iOS) || os(macOS) func testMonitor_didFinishDeferredUpdates_error() { let expectation = self.expectation(description: "Handler called") let expectedError = makeError() var expectedEvent: StandardLocationMonitor.Event? let monitor = StandardLocationMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() locationManager.updateStandardLocation(deferredError: expectedError) waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case let .didFinishDeferredUpdates(maybeError) = event, let error = maybeError { XCTAssertEqual(error as NSError, expectedError) } else { XCTFail("Unexpected event") } } #endif #if os(iOS) || os(macOS) func testMonitor_didFinishDeferredUpdates_nil() { let expectation = self.expectation(description: "Handler called") var expectedEvent: StandardLocationMonitor.Event? let monitor = StandardLocationMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() locationManager.updateStandardLocation(deferredError: nil) waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case let .didFinishDeferredUpdates(error) = event { XCTAssertNil(error) } else { XCTFail("Unexpected event") } } #endif #if os(iOS) func testMonitor_didPauseUpdates() { let expectation = self.expectation(description: "Handler called") var expectedEvent: StandardLocationMonitor.Event? let monitor = StandardLocationMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() locationManager.pauseStandardLocationUpdates() waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case .didPauseUpdates = event { } else { XCTFail("Unexpected event") } } #endif #if os(iOS) func testMonitor_didResumeUpdates() { let expectation = self.expectation(description: "Handler called") var expectedEvent: StandardLocationMonitor.Event? let monitor = StandardLocationMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() locationManager.resumeStandardLocationUpdates() waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case .didResumeUpdates = event { } else { XCTFail("Unexpected event") } } #endif #if os(iOS) || os(macOS) || os(watchOS) func testMonitor_didUpdate_error() { let expectation = self.expectation(description: "Handler called") let expectedError = makeError() var expectedEvent: StandardLocationMonitor.Event? let monitor = StandardLocationMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() locationManager.updateStandardLocation(error: expectedError) waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case let .didUpdate(info) = event, case let .error(error) = info { XCTAssertEqual(error as NSError, expectedError) } else { XCTFail("Unexpected event") } } #endif #if os(iOS) || os(macOS) || os(watchOS) func testMonitor_didUpdate_location() { let expectation = self.expectation(description: "Handler called") let expectedLocation = CLLocation() var expectedEvent: StandardLocationMonitor.Event? let monitor = StandardLocationMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() locationManager.updateStandardLocation(expectedLocation) waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case let .didUpdate(info) = event, case let .location(location) = info { XCTAssertEqual(location, expectedLocation) } else { XCTFail("Unexpected event") } } #endif #if os(iOS) || os(tvOS) || os(watchOS) func testMonitor_requestLocation() { let expectation = self.expectation(description: "Handler called") let expectedLocation = CLLocation() var expectedEvent: StandardLocationMonitor.Event? let monitor = StandardLocationMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.requestLocation() locationManager.updateStandardLocation(expectedLocation) waitForExpectations(timeout: 1) if let event = expectedEvent, case let .didUpdate(info) = event, case let .location(location) = info { XCTAssertEqual(location, expectedLocation) } else { XCTFail("Unexpected event") } } #endif #if os(iOS) func testPausesLocationUpdatesAutomatically_get() { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.pausesLocationUpdatesAutomatically = true XCTAssertTrue(monitor.pausesLocationUpdatesAutomatically) } #endif #if os(iOS) func testPausesLocationUpdatesAutomatically_set() { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.pausesLocationUpdatesAutomatically = true XCTAssertTrue(locationManager.pausesLocationUpdatesAutomatically) } #endif #if os(iOS) func testShowsBackgroundLocationIndicator_get() { if #available(iOS 11.0, *) { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } locationManager.showsBackgroundLocationIndicator = true XCTAssertTrue(monitor.showsBackgroundLocationIndicator) } } #endif #if os(iOS) func testShowsBackgroundLocationIndicator_set() { if #available(iOS 11.0, *) { let monitor = StandardLocationMonitor(queue: .main) { _ in XCTAssertEqual(OperationQueue.current, .main) } monitor.showsBackgroundLocationIndicator = true XCTAssertTrue(locationManager.showsBackgroundLocationIndicator) } } #endif private func makeError() -> NSError { return NSError(domain: "CLErrorDomain", code: CLError.Code.network.rawValue) } } // swiftlint:enable type_body_length
mit
cebd9fde804c64aa21be5183be2e6365
30.275395
80
0.636088
5.546437
false
true
false
false
ioscreator/ioscreator
IOSDragViewsGesturesTutorial/IOSDragViewsGesturesTutorial/CustomView.swift
1
1444
// // CustomView.swift // IOSDragViewsGesturesTutorial // // Created by Arthur Knopper on 11/02/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit class CustomView: UIView { var lastLocation = CGPoint(x: 0, y: 0) override init(frame: CGRect) { super.init(frame: frame) // Initialization code let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(detectPan)) self.gestureRecognizers = [panRecognizer] //randomize view color let blueValue = CGFloat.random(in: 0 ..< 1) let greenValue = CGFloat.random(in: 0 ..< 1) let redValue = CGFloat.random(in: 0 ..< 1) self.backgroundColor = UIColor(red:redValue, green: greenValue, blue: blueValue, alpha: 1.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func detectPan(_ recognizer:UIPanGestureRecognizer) { let translation = recognizer.translation(in: self.superview) self.center = CGPoint(x: lastLocation.x + translation.x, y: lastLocation.y + translation.y) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Promote the touched view self.superview?.bringSubviewToFront(self) // Remember original location lastLocation = self.center } }
mit
992ba6108bb61856275e92ef5ca3dc80
30.369565
100
0.636868
4.412844
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift
6
3012
// // TakeUntil.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class TakeUntilSinkOther<ElementType, Other, O: ObserverType> : ObserverType , LockOwnerType , SynchronizedOnType where O.E == ElementType { typealias Parent = TakeUntilSink<ElementType, Other, O> typealias E = Other fileprivate let _parent: Parent var _lock: NSRecursiveLock { return _parent._lock } fileprivate let _subscription = SingleAssignmentDisposable() init(parent: Parent) { _parent = parent #if TRACE_RESOURCES let _ = AtomicIncrement(&resourceCount) #endif } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: _parent.forwardOn(.completed) _parent.dispose() case .error(let e): _parent.forwardOn(.error(e)) _parent.dispose() case .completed: _parent._open = true _subscription.dispose() } } #if TRACE_RESOURCES deinit { let _ = AtomicDecrement(&resourceCount) } #endif } class TakeUntilSink<ElementType, Other, O: ObserverType> : Sink<O> , LockOwnerType , ObserverType , SynchronizedOnType where O.E == ElementType { typealias E = ElementType typealias Parent = TakeUntil<E, Other> fileprivate let _parent: Parent let _lock = NSRecursiveLock() // state fileprivate var _open = false init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: forwardOn(event) case .error: forwardOn(event) dispose() case .completed: forwardOn(event) dispose() } } func run() -> Disposable { let otherObserver = TakeUntilSinkOther(parent: self) let otherSubscription = _parent._other.subscribe(otherObserver) otherObserver._subscription.disposable = otherSubscription let sourceSubscription = _parent._source.subscribe(self) return Disposables.create(sourceSubscription, otherObserver._subscription) } } class TakeUntil<Element, Other>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _other: Observable<Other> init(source: Observable<Element>, other: Observable<Other>) { _source = source _other = other } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { let sink = TakeUntilSink(parent: self, observer: observer) sink.disposable = sink.run() return sink } }
mit
1adfd312b39663e5a5d5d14a869c1b18
24.091667
91
0.601793
4.589939
false
false
false
false
jackywpy/AudioKit
Tests/Tests/AKCompressor.swift
14
2016
// // main.swift // AudioKit // // Customized by Nick Arner and Aurelius Prochazka on 12/27/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: NSTimeInterval = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let filename = "AKSoundFiles.bundle/Sounds/PianoBassDrumLoop.wav" let audio = AKFileInput(filename: filename) let mono = AKMix(monoAudioFromStereoInput: audio) auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:mono) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let compressionRatio = AKLine( firstPoint: 0.5.ak, secondPoint: 2.ak, durationBetweenPoints: testDuration.ak ) let attackTime = AKLine( firstPoint: 0.ak, secondPoint: 1.ak, durationBetweenPoints: testDuration.ak ) let compressor = AKCompressor(input: audioSource, controllingInput: audioSource) compressor.compressionRatio = compressionRatio compressor.attackTime = attackTime let balance = AKBalance(input: compressor, comparatorAudioSource: audioSource) enableParameterLog( "Compression Ratio = ", parameter: compressor.compressionRatio, timeInterval:0.2 ) enableParameterLog( "Attack Time = ", parameter: compressor.attackTime, timeInterval:0.2 ) setAudioOutput(balance) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
mit
75cbce989053e5d5e782d2b71ebea687
24.518987
88
0.66369
4.977778
false
true
false
false
tjw/swift
test/Interpreter/objc_runtime_visible.swift
3
2088
// RUN: %empty-directory(%t) // RUN: %target-clang %target-cc-options -isysroot %sdk -fobjc-arc %S/Inputs/objc_runtime_visible.m -fmodules -nodefaultlibs -lc -dynamiclib -o %t/libobjc_runtime_visible.dylib -install_name @executable_path/libobjc_runtime_visible.dylib // RUN: %target-codesign %t/libobjc_runtime_visible.dylib // RUN: nm -g %t/libobjc_runtime_visible.dylib | %FileCheck %s // RUN: %target-build-swift -import-objc-header %S/Inputs/objc_runtime_visible.h %t/libobjc_runtime_visible.dylib %s -o %t/main // RUN: %target-run %t/main %t/libobjc_runtime_visible.dylib // REQUIRES: executable_test // REQUIRES: objc_interop // CHECK-NOT: HiddenClass import Foundation import StdlibUnittest extension HiddenClass { class func create() -> HiddenClass { return createHidden() } func normalMethod() -> String { return self.name } } var ObjCRuntimeVisibleTestSuite = TestSuite("ObjCRuntimeVisible") ObjCRuntimeVisibleTestSuite.test("methods") { let obj = HiddenClass.create() expectEqual("Beatrice", obj.name) expectEqual("Beatrice", obj.normalMethod()) } protocol SwiftProto { func doTheThing() -> AnyObject } extension HiddenClass: SwiftProto { func doTheThing() -> AnyObject { return self } } func callTheThing<T: SwiftProto>(_ instance: T) -> AnyObject { return instance.doTheThing() } ObjCRuntimeVisibleTestSuite.test("downcast") { let obj = HiddenClass.create() let opaque: AnyObject = obj let downcasted = opaque as? HiddenClass expectNotNil(downcasted) expectTrue(obj === downcasted) } ObjCRuntimeVisibleTestSuite.test("protocols") { let obj = HiddenClass.create() expectTrue(obj === obj.doTheThing()) let protoObj: SwiftProto = obj expectTrue(obj === protoObj.doTheThing()) expectTrue(obj === callTheThing(obj)) } ObjCRuntimeVisibleTestSuite.test("protocols/downcast") .xfail(.always("unimplemented")) .code { let obj = HiddenClass.create() let opaque: AnyObject = obj let downcasted = opaque as? SwiftProto expectNotNil(downcasted) expectTrue(obj === downcasted!.doTheThing()) } runAllTests()
apache-2.0
ea720cc466e5b244bde06f314555b555
27.216216
237
0.730843
3.789474
false
true
false
false
codestergit/swift
test/TBD/global.swift
2
660
// RUN: %target-swift-frontend -c -parse-as-library -module-name test -validate-tbd-against-ir %s public let publicLet: Int = 0 internal let internalLet: Int = 0 private let privateLet: Int = 0 public var publicVar: Int = 0 internal var internalVar: Int = 0 private var privateVar: Int = 0 public var publicVarGet: Int { get { return 0 } } internal var internalVarGet: Int { get { return 0 } } private var privateVarGet: Int { get { return 0 } } public var publicVarGetSet: Int { get { return 0 } set {} } internal var internalVarGetSet: Int { get { return 0 } set {} } private var privateVarGetSet: Int { get { return 0 } set {} }
apache-2.0
6d549e48c26a6daeadafb4194449099e
24.384615
97
0.681818
3.707865
false
false
false
false
lorentey/swift
test/decl/protocol/special/coding/class_codable_inheritance_diagnostics.swift
17
4282
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown // Non-Decodable superclasses of synthesized Decodable classes must implement // init(). class NonDecodableSuper { // expected-note {{cannot automatically synthesize 'init(from:)' because superclass does not have a callable 'init()'}} init(_: Int) {} } class NonDecodableSub : NonDecodableSuper, Decodable { // expected-error {{type 'NonDecodableSub' does not conform to protocol 'Decodable'}} } // Non-Decodable superclasses of synthesized Decodable classes must have // designated init()'s. class NonDesignatedNonDecodableSuper { convenience init() { // expected-note {{cannot automatically synthesize 'init(from:)' because implementation would need to call 'init()', which is not designated}} self.init(42) } init(_: Int) {} } class NonDesignatedNonDecodableSub : NonDesignatedNonDecodableSuper, Decodable { // expected-error {{type 'NonDesignatedNonDecodableSub' does not conform to protocol 'Decodable'}} } // Non-Decodable superclasses of synthesized Decodable classes must have an // accessible init(). class InaccessibleNonDecodableSuper { private init() {} // expected-note {{cannot automatically synthesize 'init(from:)' because implementation would need to call 'init()', which is inaccessible due to 'private' protection level}} } class InaccessibleNonDecodableSub : InaccessibleNonDecodableSuper, Decodable { // expected-error {{type 'InaccessibleNonDecodableSub' does not conform to protocol 'Decodable'}} } // Non-Decodable superclasses of synthesized Decodable classes must have a // non-failable init(). class FailableNonDecodableSuper { init?() {} // expected-note {{cannot automatically synthesize 'init(from:)' because implementation would need to call 'init()', which is failable}} } class FailableNonDecodableSub : FailableNonDecodableSuper, Decodable { // expected-error {{type 'FailableNonDecodableSub' does not conform to protocol 'Decodable'}} } // Subclasses of classes whose Decodable synthesis fails should not inherit // conformance. class FailedSynthesisDecodableSuper : Decodable { // expected-error 2{{type 'FailedSynthesisDecodableSuper' does not conform to protocol 'Decodable'}} enum CodingKeys : String, CodingKey { case nonexistent // expected-note 2{{CodingKey case 'nonexistent' does not match any stored properties}} } } class FailedSynthesisDecodableSub : FailedSynthesisDecodableSuper { // expected-note {{did you mean 'init'?}} func foo() { // Decodable should fail to synthesis or be inherited. let _ = FailedSynthesisDecodableSub.init(from:) // expected-error {{type 'FailedSynthesisDecodableSub' has no member 'init(from:)'}} } } // Subclasses of Decodable classes which can't inherit their initializers should // produce diagnostics. class DecodableSuper : Decodable { var value = 5 } class DecodableSubWithoutInitialValue : DecodableSuper { // expected-error {{class 'DecodableSubWithoutInitialValue' has no initializers}} // expected-note@-1 {{did you mean to override 'init(from:)'?}} var value2: Int // expected-note {{stored property 'value2' without initial value prevents synthesized initializers}} } class DecodableSubWithInitialValue : DecodableSuper { var value2 = 10 } // Subclasses of Codable classes which can't inherit their initializers should // produce diagnostics. class CodableSuper : Codable { var value = 5 } class CodableSubWithoutInitialValue : CodableSuper { // expected-error {{class 'CodableSubWithoutInitialValue' has no initializers}} // expected-note@-1 {{did you mean to override 'init(from:)' and 'encode(to:)'?}} var value2: Int // expected-note {{stored property 'value2' without initial value prevents synthesized initializers}} } // We should only mention encode(to:) in the diagnostic if the subclass does not // override it. class EncodableSubWithoutInitialValue : CodableSuper { // expected-error {{class 'EncodableSubWithoutInitialValue' has no initializers}} // expected-note@-1 {{did you mean to override 'init(from:)'?}} var value2: Int // expected-note {{stored property 'value2' without initial value prevents synthesized initializers}} override func encode(to: Encoder) throws {} } class CodableSubWithInitialValue : CodableSuper { var value2 = 10 }
apache-2.0
27601f42b24980c5358aae95e2c94a17
44.073684
194
0.761794
4.747228
false
false
false
false
zvonicek/ImageSlideshow
ImageSlideshow/Classes/Core/PageIndicator.swift
1
2589
// // PageIndicator.swift // ImageSlideshow // // Created by Petr Zvoníček on 27.05.18. // import UIKit /// Cusotm Page Indicator can be used by implementing this protocol public protocol PageIndicatorView: class { /// View of the page indicator var view: UIView { get } /// Current page of the page indicator var page: Int { get set } /// Total number of pages of the page indicator var numberOfPages: Int { get set} } extension UIPageControl: PageIndicatorView { public var view: UIView { return self } public var page: Int { get { return currentPage } set { currentPage = newValue } } open override func sizeToFit() { var frame = self.frame frame.size = size(forNumberOfPages: numberOfPages) frame.size.height = 30 self.frame = frame } public static func withSlideshowColors() -> UIPageControl { let pageControl = UIPageControl() if #available(iOS 13.0, *) { pageControl.currentPageIndicatorTintColor = UIColor { traits in traits.userInterfaceStyle == .dark ? .white : .lightGray } } else { pageControl.currentPageIndicatorTintColor = .lightGray } if #available(iOS 13.0, *) { pageControl.pageIndicatorTintColor = UIColor { traits in traits.userInterfaceStyle == .dark ? .systemGray : .black } } else { pageControl.pageIndicatorTintColor = .black } return pageControl } } /// Page indicator that shows page in numeric style, eg. "5/21" public class LabelPageIndicator: UILabel, PageIndicatorView { public var view: UIView { return self } public var numberOfPages: Int = 0 { didSet { updateLabel() } } public var page: Int = 0 { didSet { updateLabel() } } public override init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { self.textAlignment = .center } private func updateLabel() { text = "\(page+1)/\(numberOfPages)" } public override func sizeToFit() { let maximumString = String(repeating: "8", count: numberOfPages) as NSString self.frame.size = maximumString.size(withAttributes: [.font: font as Any]) } }
mit
21f32edfdc0664c910991807d77a00f9
23.40566
84
0.587553
4.835514
false
false
false
false
DeveloperLx/LxAppleOfficialFontManager-swift
LxAppleOfficialFontManagerDemo/LxAppleOfficialFontManagerDemo/ViewController.swift
1
1692
// // ViewController.swift // LxAppleOfficialFontManagerDemo // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 100)) label.text = "Preparing..." label.textAlignment = .Center label.textColor = UIColor.blueColor() label.numberOfLines = 0 label.center = view.center view.addSubview(label) let downloadableAvailableFontDescriptors = LxAppleOfficialFontManager.availableAppleFontDescriptors()! let randomFontDescriptor = downloadableAvailableFontDescriptors[Int(arc4random()) % downloadableAvailableFontDescriptors.count] let randomFontName = randomFontDescriptor.fontAttributes()[UIFontDescriptorNameAttribute] as! String LxAppleOfficialFontManager.downloadFontNamed(name: randomFontName, progressCallBack: { (progress) -> () in println("progress = \(progress)") dispatch_async(dispatch_get_main_queue(), { () -> Void in label.text = "\(progress) downloaded" }) }, finishedCallBack: { (font) -> () in println("font = \(font)") dispatch_async(dispatch_get_main_queue(), { () -> Void in label.text = "This is apple offical font \(font!.fontName)!" label.font = font }) }, failedCallBack: { (error) -> () in println("error = \(error)") }) } }
apache-2.0
bebd31a085fa25a00025f850c900b444
35
135
0.563239
5.23839
false
false
false
false
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Highlight/BarChartHighlighter.swift
6
7943
// // ChartBarHighlighter.swift // Charts // // Created by Daniel Cohen Gindi on 26/7/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class BarChartHighlighter: ChartHighlighter { open override func getHighlight(x: CGFloat, y: CGFloat) -> ChartHighlight? { if let barData = self.chart?.data as? BarChartData { let xIndex = getXIndex(x) let baseNoSpace = getBase(x) let setCount = barData.dataSetCount var dataSetIndex = Int(baseNoSpace) % setCount if dataSetIndex < 0 { dataSetIndex = 0 } else if dataSetIndex >= setCount { dataSetIndex = setCount - 1 } guard let selectionDetail = getSelectionDetail(xIndex: xIndex, y: y, dataSetIndex: dataSetIndex) else { return nil } if let set = barData.getDataSetByIndex(dataSetIndex) as? IBarChartDataSet, set.isStacked { var pt = CGPoint(x: 0.0, y: y) // take any transformer to determine the x-axis value self.chart?.getTransformer(set.axisDependency).pixelToValue(&pt) return getStackedHighlight(selectionDetail: selectionDetail, set: set, xIndex: xIndex, yValue: Double(pt.y)) } return ChartHighlight(xIndex: xIndex, value: selectionDetail.value, dataIndex: selectionDetail.dataIndex, dataSetIndex: selectionDetail.dataSetIndex, stackIndex: -1) } return nil } open override func getXIndex(_ x: CGFloat) -> Int { if let barData = self.chart?.data as? BarChartData { if !barData.isGrouped { return super.getXIndex(x) } else { let baseNoSpace = getBase(x) let setCount = barData.dataSetCount var xIndex = Int(baseNoSpace) / setCount let valCount = barData.xValCount if xIndex < 0 { xIndex = 0 } else if xIndex >= valCount { xIndex = valCount - 1 } return xIndex } } else { return 0 } } open override func getSelectionDetail(xIndex: Int, y: CGFloat, dataSetIndex: Int?) -> ChartSelectionDetail? { if let barData = self.chart?.data as? BarChartData { let dataSetIndex = dataSetIndex ?? 0 if let dataSet = (barData.dataSetCount > dataSetIndex ? barData.getDataSetByIndex(dataSetIndex) : nil) { let yValue = dataSet.yValForXIndex(xIndex) if yValue.isNaN { return nil } return ChartSelectionDetail(value: yValue, dataSetIndex: dataSetIndex, dataSet: dataSet) } return nil } else { return nil } } /// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected. /// - parameter selectionDetail: the selection detail to work with /// - parameter set: /// - parameter xIndex: /// - parameter yValue: /// - returns: open func getStackedHighlight(selectionDetail: ChartSelectionDetail, set: IBarChartDataSet, xIndex: Int, yValue: Double) -> ChartHighlight? { guard let entry = set.entryForXIndex(xIndex) as? BarChartDataEntry else { return nil } if entry.values == nil { return ChartHighlight(xIndex: xIndex, value: entry.value, dataIndex: selectionDetail.dataIndex, dataSetIndex: selectionDetail.dataSetIndex, stackIndex: -1) } if let ranges = getRanges(entry: entry), ranges.count > 0 { let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue) return ChartHighlight(xIndex: xIndex, value: entry.positiveSum - entry.negativeSum, dataIndex: selectionDetail.dataIndex, dataSetIndex: selectionDetail.dataSetIndex, stackIndex: stackIndex, range: ranges[stackIndex]) } return nil } /// Returns the index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter. /// - parameter entry: /// - parameter value: /// - returns: open func getClosestStackIndex(ranges: [ChartRange]?, value: Double) -> Int { if ranges == nil { return 0 } var stackIndex = 0 for range in ranges! { if range.contains(value) { return stackIndex } else { stackIndex += 1 } } let length = max(ranges!.count - 1, 0) return (value > ranges![length].to) ? length : 0 } /// Returns the base x-value to the corresponding x-touch value in pixels. /// - parameter x: /// - returns: open func getBase(_ x: CGFloat) -> Double { guard let barData = self.chart?.data as? BarChartData else { return 0.0 } // create an array of the touch-point var pt = CGPoint() pt.x = CGFloat(x) // take any transformer to determine the x-axis value self.chart?.getTransformer(ChartYAxis.AxisDependency.left).pixelToValue(&pt) let xVal = Double(pt.x) let setCount = barData.dataSetCount // calculate how often the group-space appears let steps = Int(xVal / (Double(setCount) + Double(barData.groupSpace))) let groupSpaceSum = Double(barData.groupSpace) * Double(steps) let baseNoSpace = xVal - groupSpaceSum return baseNoSpace } /// Splits up the stack-values of the given bar-entry into Range objects. /// - parameter entry: /// - returns: open func getRanges(entry: BarChartDataEntry) -> [ChartRange]? { let values = entry.values if (values == nil) { return nil } var negRemain = -entry.negativeSum var posRemain: Double = 0.0 var ranges = [ChartRange]() ranges.reserveCapacity(values!.count) for i in 0 ..< values!.count { let value = values![i] if value < 0 { ranges.append(ChartRange(from: negRemain, to: negRemain + abs(value))) negRemain += abs(value) } else { ranges.append(ChartRange(from: posRemain, to: posRemain+value)) posRemain += value } } return ranges } }
mit
eaffee440993a29479d23c93c504ed01
31.028226
133
0.494146
5.637331
false
false
false
false
visenze/visearch-sdk-swift
ViSearchSDK/ViSearchSDK/Classes/Request/ProductSearch/ViSearchByImageParam.swift
1
6331
// // ViSearchByImageParam.swift // ViSearchSDK // // Created by visenze on 8/3/21. // import Foundation import UIKit /// This class contains the specific parameters only required when calling the Search By Image API. It inherits /// ViBaseProductSearchParam which contains all general parameters open class ViSearchByImageParam : ViBaseProductSearchParam { public var imUrl : String? = nil public var imId : String? = nil public var image : UIImage? = nil public var box : ViBox? = nil public var detection : String? = nil public var detectionLimit : Int? = nil public var detectionSensitivity : String? = nil public var searchAllObjects : Bool? = nil public var imgSettings : ViImageSettings = ViImageSettings() public var points: [ViPoint] = [] public var compress_box: String? = nil /// Constructor using image URL /// /// - parameter imUrl: URL to an image /// /// - returns: Nil if paramter is an empty string public init?(imUrl: String){ self.imUrl = imUrl if imUrl.isEmpty { print("\(type(of: self)).\(#function)[line:\(#line)] - error: imUrl is missing") return nil } } /// Constructor using image ID /// /// - parameter imId: Image ID can be found in any image retrieved from the server /// /// - returns: Nil if paramter is an empty string public init?(imId: String){ self.imId = imId if imId.isEmpty { print("\(type(of: self)).\(#function)[line:\(#line)] - error: imId is missing") return nil } } /// Constructor using image file /// /// - parameter image: Loaded image data public init(image: UIImage){ self.image = image } /// Get the compressed/resize image data /// /// - returns: Compressed jpegData public func getCompressedImageData() -> Data? { if let image = image { let quality = imgSettings.quality; // maxWidth should not larger than 1024 pixels let maxWidth = CGFloat(min(imgSettings.maxWidth, 1024)); var actualHeight : CGFloat = image.size.height * image.scale; var actualWidth : CGFloat = image.size.width * image.scale; let maxHeight : CGFloat = maxWidth var imgRatio : CGFloat = actualWidth/actualHeight; let maxRatio : CGFloat = maxWidth/maxHeight; if (actualHeight > maxHeight || actualWidth > maxWidth) { if(imgRatio < maxRatio) { // adjust width according to maxHeight imgRatio = maxHeight / actualHeight; actualWidth = imgRatio * actualWidth; actualHeight = maxHeight; } else if(imgRatio > maxRatio) { // adjust height according to maxWidth imgRatio = CGFloat(imgSettings.maxWidth) / actualWidth; actualHeight = imgRatio * actualHeight; actualWidth = maxWidth; } else { actualHeight = maxHeight; actualWidth = maxWidth; } } let rect : CGRect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight); UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0); image.draw(in: rect) let img = UIGraphicsGetImageFromCurrentImageContext(); let imageData : Data = img!.jpegData(compressionQuality: CGFloat(quality))!; UIGraphicsEndImageContext(); // if there is a box, we need to generate a compress box if let box = box , let compressed_image = UIImage(data: imageData) { let scale : CGFloat = (compressed_image.size.height > compressed_image.size.width) ? compressed_image.size.height * compressed_image.scale / (image.size.height * image.scale) : compressed_image.size.width * compressed_image.scale / (image.size.width * image.scale); let scaleX1 = Int(scale * CGFloat(box.x1) ) let scaleX2 = Int(scale * CGFloat(box.x2) ) let scaleY1 = Int(scale * CGFloat(box.y1) ) let scaleY2 = Int(scale * CGFloat(box.y2) ) self.compress_box = "\(scaleX1),\(scaleY1),\(scaleX2),\(scaleY2)" } else { self.compress_box = nil } return imageData } return nil } /// Get a dictionary containing all of this class' member variables as keys and their corresponding values /// /// - returns: A dictionary representing this class public override func toDict() -> [String: Any] { var dict = super.toDict() if let imUrl = imUrl { dict["im_url"] = imUrl } if let imId = imId { dict["im_id"] = imId } if let b = box { if let compress_box = self.compress_box { dict["box"] = compress_box } else { dict["box"] = "\(b.x1),\(b.y1),\(b.x2),\(b.y2)" } } if let detection = detection { dict["detection"] = detection } if let detectionLimit = detectionLimit { dict["detection_limit"] = String(detectionLimit) } if let detectionSensitivity = detectionSensitivity { dict["detection_sensitivity"] = detectionSensitivity } if let searchAllObjects = searchAllObjects { dict["search_all_objects"] = searchAllObjects ? "true" : "false" } if points.count > 0 { var pointArr : [String] = [] for point in points { let pointComma = "\(point.x),\(point.y)" pointArr.append(pointComma) } dict["point"] = pointArr } return dict } }
mit
4f547e02616088c8a1654324fd723c07
32.855615
113
0.531038
5.060751
false
false
false
false
jdbateman/Lendivine
Lendivine/CartTableViewCell.swift
1
7548
// // CartTableViewCell.swift // Lendivine // // Created by john bateman on 11/16/15. // Copyright © 2015 John Bateman. All rights reserved. // // This custom table view cell is used in the CartTableViewController to display summary information about a loan. The RemoveFromCart button is a subview of the cell. When it is selected the data associated with the cell must be deleted. That is handled here. import UIKit class CartTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var loanImageView: UIImageView! @IBOutlet weak var changeDonationButton: UIButton! @IBOutlet weak var countryLabel: UILabel! @IBOutlet weak var flagImageView: UIImageView! // User selected the change donation button in the cell. Present donation amount options in an action sheet. @IBAction func onChangeDonationButton(sender: AnyObject) { presentDonationAmounts(sender) } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } // Display a list of user selectable donation amounts in an action sheet. func presentDonationAmounts(sender: AnyObject) { let alertController = UIAlertController(title: nil, message: "Select an amount to lend.", preferredStyle: .ActionSheet) let Action25 = UIAlertAction(title: "$25", style: .Default) { (action) in // update donation amount on button text self.changeDonationButton.imageView!.image = self.imageForButton(25) // update donation amount in cart item self.updateCartItem(sender as! UIView, donationAmount: 25) } alertController.addAction(Action25) let Action50 = UIAlertAction(title: "$50", style: .Default) { (action) in // update donation amount on button text self.changeDonationButton.imageView!.image = self.imageForButton(50) // update donation amount in cart item self.updateCartItem(sender as! UIView, donationAmount: 50) } alertController.addAction(Action50) let Action100 = UIAlertAction(title: "$100", style: .Default) { (action) in // update donation amount on button text self.changeDonationButton.imageView!.image = self.imageForButton(100) // update donation amount in cart item self.updateCartItem(sender as! UIView, donationAmount: 100) } alertController.addAction(Action100) // present the controller let controller = parentViewController if let controller = controller { controller.presentViewController(alertController, animated: true) { // ... } } } // Update the donation amount of the cart item associated with this cell. func updateCartItem(subView: UIView, donationAmount: NSNumber) { let indexPath = getIndexPathForCellContainingSubview(subView) if let indexPath = indexPath { let index = indexPath.row let cartViewController = getTableViewControllerForCellContainingSubview(subView) let cartItem = cartViewController.cart!.items[index] cartItem.donationAmount = donationAmount // save the context to persist the updated cart property to core data CoreDataContext.sharedInstance().saveCartContext() } } // Set button image to donation amount func imageForButton(donationAmount: NSNumber) -> UIImage { var xCoord = 15 switch donationAmount.intValue { case 0...9: xCoord = 14 case 10...99: xCoord = 18 case 100...999: xCoord = 10 default: xCoord = 15 } let buttonText: String = "$" + donationAmount.stringValue let donationImage: UIImage = ViewUtility.createImageFromText(buttonText, backingImage: UIImage(named:cartDonationImageName)!, atPoint: CGPointMake(CGFloat(xCoord), 4)) return donationImage } // Return an index path for the cell containing the specified subview of the cell. func getIndexPathForCellContainingSubview(subview: UIView) -> NSIndexPath? { // Find the cell starting from the subview. let contentView = subview.superview! let cell = contentView.superview as! CartTableViewCell // Find the tableView by walking the view hierarchy until a UITableView class is encountered. var view = cell.superview while ( (view != nil) && (view?.isKindOfClass(UITableView) == false) ) { view = view!.superview } let tableView: UITableView = view as! UITableView // Get the indexPath associated with this table cell let indexPath = tableView.indexPathForCell(cell) return indexPath } // Return the CartTableViewController for the cell containing the specified subview of the cell. func getTableViewControllerForCellContainingSubview(subview: UIView) -> CartTableViewController { // Find the cell starting from the subview. let contentView = subview.superview! let cell = contentView.superview as! CartTableViewCell // Find the tableView by walking the view hierarchy until a UITableView class is encountered. var view = cell.superview while ( (view != nil) && (view?.isKindOfClass(UITableView) == false) ) { view = view!.superview } let tableView: UITableView = view as! UITableView let cartViewController = tableView.dataSource as! CartTableViewController return cartViewController } // Remove cell containing the selected button from the cart table view controller, and remove the associated loan from the cart. func removeFromCart(sender: UIButton) { // Find the cell starting from the button. let button = sender let contentView = button.superview! let cell = contentView.superview as! CartTableViewCell // Find the tableView by walking the view hierarchy until a UITableView class is encountered. var view = cell.superview while ( (view != nil) && (view?.isKindOfClass(UITableView) == false) ) { view = view!.superview } let tableView: UITableView = view as! UITableView // Get the indexPath associated with this table cell let indexPath = tableView.indexPathForCell(cell) // Remove the loan from the cart. let cartViewController = tableView.dataSource as! CartTableViewController let index = indexPath!.row cartViewController.cart?.removeItemByIndex(index) // refresh the table view dispatch_async(dispatch_get_main_queue()) { tableView.reloadData() } } } extension UIView { var parentViewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.nextResponder() if parentResponder is UIViewController { return parentResponder as! UIViewController! } } return nil } }
mit
ee6d5a6b2e907d4945ca481a498443a2
38.931217
260
0.644229
5.488727
false
false
false
false
quran/quran-ios
Sources/TranslationService/TranslationDeleter.swift
1
2167
// // TranslationDeleter.swift // Quran // // Created by Mohamed Afifi on 3/12/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Foundation import PromiseKit public struct TranslationDeleter { let persistence: ActiveTranslationsPersistence let selectedTranslationsPreferences = SelectedTranslationsPreferences.shared public init(databasesPath: String) { persistence = SQLiteActiveTranslationsPersistence(directory: databasesPath) } public func deleteTranslation(_ translation: Translation) -> Promise<Translation> { // update the selected translations let translations = selectedTranslationsPreferences.selectedTranslations var updatedTranslations: [Int] = [] for id in translations where translation.id != id { updatedTranslations.append(id) } if translations != updatedTranslations { selectedTranslationsPreferences.selectedTranslations = updatedTranslations } return DispatchQueue.global() .async(.promise) { // delete from disk translation.possibleFileNames.forEach { fileName in let url = Translation.localTranslationsURL.appendingPathComponent(fileName) try? FileManager.default.removeItem(at: url) } } .map { () -> Translation in var translation = translation translation.installedVersion = nil try self.persistence.update(translation) return translation } } }
apache-2.0
06927d0d1df212a8ed837d45904a135e
36.362069
95
0.671435
5.209135
false
false
false
false
doncl/shortness-of-pants
ScrollingTabPager/ScrollingTabPager/ScrollingTabPagerCollectionViewProtocols.swift
1
5922
// // ScrollingTabPagerCollectionViewProtocols.swift // ScrollingTabPager // // Created by Don Clore on 3/8/21. // import UIKit extension ScrollingTabPager: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return titles.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HeaderCell.cellId, for: indexPath) as? HeaderCell else { fatalError("Should never happen") } cell.selectedColor = designObject.headerTextColor if let deSelectedColor = designObject.headerDeSelectedTextColor { cell.deSelectedColor = deSelectedColor } cell.backgroundColor = collectionView.backgroundColor cell.contentView.backgroundColor = collectionView.backgroundColor cell.label.text = titles[indexPath.item] cell.label.textColor = designObject.headerTextColor switch designObject.headerAlignment { case .leading, .leadingStayVisible: cell.label.textAlignment = NSTextAlignment.left case .center: cell.label.textAlignment = NSTextAlignment.center } cell.label.textColor = cell.isSelected ? cell.selectedColor : cell.normalColor cell.label.font = designObject.headerFont cell.extraTabWidth = designObject.extraTabWidth cell.sizeToFit() return cell } } extension ScrollingTabPager: UICollectionViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { switch designObject.headerAlignment { case .leading, .leadingStayVisible: break case .center: scrollView.setContentOffset(CGPoint.zero, animated: false) } } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? HeaderCell, let header = collectionView as? ScrollingTabHeader else { return } cell.isSelected = true cell.setNeedsLayout() currentIndex = indexPath.item header.indexPathForUnderline = indexPath pager.select(viewControllerIndex: currentIndex) switch designObject.headerAlignment { case .center, .leading: let scrollPosition = getScrollPositionForAlignmentStyle() collectionView.scrollToItem(at: indexPath, at: scrollPosition, animated: true) case .leadingStayVisible: break } collectionView.setNeedsLayout() collectionView.layoutIfNeeded() showOrHideArrowAsAppropriate(contentWidth: collectionView.contentSize.width, currIndex: indexPath.item) pageSelectedWrapper(index: indexPath.item) } public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? HeaderCell else { return } cell.isSelected = false } } public class HeaderCell: UICollectionViewCell { public static let cellId: String = "HeaderCell" public var selectedColor: UIColor = UIColor.black public var deSelectedColor: UIColor? static let alphaComponentBase: CGFloat = 0.4 var font: UIFont = UIFont.boldSystemFont(ofSize: 16.0) { didSet { label.font = font } } public var normalColor: UIColor { if let deselect = deSelectedColor { return deselect } return self.selectedColor.withAlphaComponent(HeaderCell.alphaComponentBase) } public var extraTabWidth: CGFloat = 0 { didSet { setNeedsLayout() } } var interpolatedColor: UIColor? { didSet { if let color = interpolatedColor { label.textColor = color } } } public let label: UILabel = UILabel() override public init(frame: CGRect) { super.init(frame: frame) secondPhaseInitializer() } public static func widthThatFits(_ title: String, extraTabWidth: CGFloat, color: UIColor, font: UIFont) -> CGFloat { return sizeForCell(with: title, extraTabWidth: extraTabWidth, color: color, font: font).width } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) secondPhaseInitializer() } static func sizeForCell(with title: String, extraTabWidth: CGFloat, color: UIColor, font: UIFont) -> CGSize { let ns = NSString(string: title) let size = ns.size(withAttributes: [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: font]) return CGSize(width: size.width + extraTabWidth, height: size.height) } override public var isSelected: Bool { get { return super.isSelected } set { label.textColor = newValue ? selectedColor : normalColor interpolatedColor = nil super.isSelected = newValue label.setNeedsLayout() label.setNeedsDisplay() } } fileprivate func secondPhaseInitializer() { contentView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.textColor = normalColor label.font = font label.clipsToBounds = true label.backgroundColor = .clear label.baselineAdjustment = UIBaselineAdjustment.alignCenters NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: leadingAnchor), contentView.trailingAnchor.constraint(equalTo: trailingAnchor), contentView.topAnchor.constraint(equalTo: topAnchor), contentView.bottomAnchor.constraint(equalTo: bottomAnchor), label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), ]) clipsToBounds = true } }
mit
f1399a1327c825df4c205b27fe3fa764
31.184783
133
0.730328
5.140625
false
false
false
false
fqhuy/minimind
minimind/core/matrix_bool_extension.swift
1
3074
// // matrix_bool_extension.swift // minimind // // Created by Phan Quoc Huy on 6/10/17. // Copyright © 2017 Phan Quoc Huy. All rights reserved. // import Foundation import Accelerate //MARK: COMPARISONS public extension Matrix where T == Bool { public func any() -> Bool { return minimind.any(self) } public func all() -> Bool { return minimind.all(self) } } public func isnan<T: ScalarType>(_ mat: Matrix<T>) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, mat.grid.map{ $0.isNaN } ) } public func all(_ mat: Matrix<Bool>) -> Bool { return all(mat.grid) } public func any(_ mat: Matrix<Bool>) -> Bool { return any(mat.grid) } public func ==<T: Equatable>(_ mat: Matrix<T>, _ t: T) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid == t)) } public func >=<T: Comparable>(_ mat: Matrix<T>, _ t: T) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid >= t)) } public func <= <T: Comparable>(_ mat: Matrix<T>, _ t: T) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid <= t)) } public func > <T: Comparable>(_ mat: Matrix<T>, _ t: T) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid > t)) } public func < <T: Comparable>(_ mat: Matrix<T>, _ t: T) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid < t)) } public func ==<T: Equatable>(_ t: T, _ mat: Matrix<T>) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid == t)) } public func >=<T: Comparable>(_ t: T, _ mat: Matrix<T>) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid >= t)) } public func <= <T: Comparable>(_ t: T, _ mat: Matrix<T>) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid <= t)) } public func > <T: Comparable>(_ t: T, _ mat: Matrix<T>) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid > t)) } public func < <T: Comparable>(_ t: T, _ mat: Matrix<T>) -> Matrix<Bool> { return Matrix<Bool>(mat.rows, mat.columns, (mat.grid < t)) } public func ==<T: Equatable>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<Bool> { checkMatrices(lhs, rhs, "same") return Matrix<Bool>(lhs.rows, lhs.columns, (lhs.grid == rhs.grid)) } public func >=<T: Comparable>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<Bool> { checkMatrices(lhs, rhs, "same") return Matrix<Bool>(lhs.rows, lhs.columns, (lhs.grid >= rhs.grid)) } public func <= <T: Comparable>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<Bool> { checkMatrices(lhs, rhs, "same") return Matrix<Bool>(lhs.rows, lhs.columns, (lhs.grid <= rhs.grid)) } public func > <T: Comparable>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<Bool> { checkMatrices(lhs, rhs, "same") return Matrix<Bool>(lhs.rows, lhs.columns, (lhs.grid > rhs.grid)) } public func < <T: Comparable>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<Bool> { checkMatrices(lhs, rhs, "same") return Matrix<Bool>(lhs.rows, lhs.columns, (lhs.grid < rhs.grid)) }
mit
145c4acb6d90e6ad39cd6a94701471d3
30.357143
84
0.612756
2.986395
false
false
false
false
robertBojor/APImatic
Pod/Classes/APImatic.swift
1
14781
import Foundation public class APImatic: NSObject { // MARK: Public variables & constants public static let sharedInstance:APImatic = APImatic() public var APIBaseURL = "" public var APIVersion = "" public var APIUrlSeparator = "/" public var APILogging = false public enum Methods:String { case DELETE = "DELETE" case GET = "GET" case HEAD = "HEAD" case OPTIONS = "OPTIONS" case POST = "POST" case PUT = "PUT" case TRACE = "TRACE" } public enum MimeTypes:String { case ApplicationAtomXML = "application/atom+xml" case ApplicationVnd = "application/vnd.dart" case ApplicationECMAScript = "application/ecmascript" case ApplicationEDIX12 = "application/EDI-X12" case ApplicationEDIFACT = "application/EDIFACT" case ApplicationJSON = "application/json" case ApplicationJavaScript = "application/javascript" case ApplicationOctetStream = "application/octet-stream" case ApplicationOGG = "application/ogg" case ApplicationDashXML = "application/dash+xml" case ApplicationPDF = "application/pdf" case ApplicationPostScript = "application/postscript" case ApplicationRDF = "application/rdf+xml" case ApplicationRSS = "application/rss+xml" case ApplicationSOAP = "application/soap+xml" case ApplicationWOFF = "application/font-woff" case ApplicationXHTML = "application/xhtml+xml" case ApplicationXML = "application/xml" case ApplicationDTD = "application/xml-dtd" case ApplicationXOP = "application/xop+xml" case ApplicationZIP = "application/zip" case ApplicationGzip = "application/gzip" case ApplicationNACL = "application/x-nacl" case ApplicationPNACL = "application/x-pnacl" case ApplicationSMIL = "application/smil+xml" case AudioBasic = "audio/basic" case AudioL24 = "audio/L24" case AudioMP4 = "audio/mp4" case AudioMPEG = "audio/mpeg" case AudioOGG = "audio/ogg" case AudioFlac = "audio/flac" case AudioOpus = "audio/opus" case AudioVorbis = "audio/vorbis" case AudioRealAudio = "audio/vnd.rn-realaudio" case AudioWAV = "audio/vnd.wave" case AudioWebM = "audio/webm" case ImageGIF = "image/gif" case ImageJPEG = "image/jpeg" case ImagePJPEG = "image/pjpeg" case ImagePNG = "image/png" case ImageSVG = "image/svg+xml" case ImageTiff = "image/tiff" case ImageDjVu = "image/vnd.djvu" case MessageHTTP = "message/http" case MessageIMDN = "message/imdn+xml" case MessagePartial = "message/partial" case MessageRFC822 = "message/rfc822" case ModelIGS = "model/iges" case ModelMesh = "model/mesh" case ModelVRML = "model/vrml" case ModelX3DISO = "model/x3d+binary" case ModelX3DFastInfoSet = "model/x3d+fastinfoset" case ModelX3DVRML = "model/x3d-vrml" case ModelX3DXML = "model/x3d+xml" case MultipartMixed = "multipart/mixed" case MultipartAlternative = "multipart/alternative" case MultipartRelated = "multipart/related" case MultipartFormData = "multipart/form-data" case MultipartSigned = "multipart/signed" case MultipartEncrypted = "multipart/encrypted" case TextCMD = "text/cmd" case TextCSS = "text/css" case TextCSV = "text/csv" case TextHTML = "text/html" case TextPlain = "text/plain" case TextRTF = "text/rtf" case TextvCard = "text/vcard" case TextALanguage = "text/vnd.a" case TextABCNotation = "text/vnd.abc" case TextXML = "text/xml" case VideoAVI = "video/avi" case VideoMPEG = "video/mpeg" case VideoMP4 = "video/mp4" case VideoOGG = "video/ogg" case VideoQuicktime = "video/quicktime" case VideoWebM = "video/webm" case VideoMatroska = "video/x-matroska" case VideoWMV = "video/x-ms-wmv" case VideoFLV = "video/x-flv" } // MARK: - // MARK: Private variables & constants private let APImaticBoundary = "__APIMATIC_HELPER_BOUNDARY__" private var lastData:NSData! private var lastResponse:NSURLResponse! private var lastError:NSError! private var lastStatusCode:NSInteger! // MARK: - // MARK: APImator initialiser public override init() { self.lastData = nil self.lastResponse = nil self.lastError = nil self.lastStatusCode = 0 } // MARK: - // MARK: Public methods public func sendRequest( usingMethod:Methods, toEndpoint:String, withHeaders:Dictionary<String,String>?, andParameters:Dictionary<String,String>?, withSuccessHandler:(responseData:NSData?, responseCode:NSInteger?) -> Void, andFailureHandler:(responseData:NSData?, responseCode:NSInteger?, responseError:NSError?) -> Void) -> Void { let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) let finalEndpointURL = self.APIBaseURL + self.APIUrlSeparator + (!self.APIVersion.isEmpty ? self.APIVersion + self.APIUrlSeparator : "") + toEndpoint if self.APILogging { print("[APImatic] Sending \(usingMethod.rawValue) request to URL: \(finalEndpointURL)") } var URL = NSURL(string: finalEndpointURL) if usingMethod.rawValue == Methods.GET.rawValue { if let callParams = andParameters { URL = self.NSURLByAppendingQueryParameters(URL!, queryParameters: callParams) if self.APILogging { print("[APImatic] Added parameters to URL! New URL is: \(URL?.absoluteString)") } } } let request = NSMutableURLRequest(URL: URL!) request.HTTPMethod = usingMethod.rawValue request.addValue("application/json", forHTTPHeaderField: "Accept") if usingMethod.rawValue == Methods.POST.rawValue { request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } if let callHeaders = withHeaders { for(key, val) in callHeaders { request.addValue("\(val)", forHTTPHeaderField: "\(key)") } if self.APILogging { print("[APImatic] Added headers to call") } } if usingMethod.rawValue == Methods.POST.rawValue { if let callParams = andParameters { let queryParameters = stringFromQueryParameters(callParams) request.HTTPBody = queryParameters.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) if self.APILogging { print("[APImatic] Added parameters to request body") } } } let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData?, response : NSURLResponse?, error : NSError?) -> Void in if let finalResponse = response { self.lastStatusCode = (finalResponse as! NSHTTPURLResponse).statusCode self.lastResponse = finalResponse } else { self.lastStatusCode = 0 self.lastResponse = nil } if self.APILogging { print("[APImatic] Returned from request call with response code: \(self.lastStatusCode)") } if let finalData = data { self.lastData = finalData } else { self.lastData = nil } if let finalError = error { self.lastError = finalError } else { self.lastError = nil } switch(self.lastStatusCode) { case 200, 201, 204, 304: if self.APILogging { print("[APImatic] Finished! Calling success handler...") } withSuccessHandler(responseData: self.lastData, responseCode: self.lastStatusCode) break default: if self.APILogging { print("[APImatic] Finished! Calling failure handler...") } andFailureHandler(responseData: self.lastData, responseCode: self.lastStatusCode, responseError: self.lastError) } }) if self.APILogging { print("[APImatic] Started request call") } task.resume() } public func sendFile( toEndpoint: String, withHeaders: Dictionary<String,String>?, andParameters: Dictionary<String,String>?, withFilePath: String?, andFileName: String?, andFileContentType: MimeTypes?, withSuccessHandler:(responseData:NSData?, responseCode:NSInteger?) -> Void, andFailureHandler:(responseData:NSData?, responseCode:NSInteger?, responseError:NSError?) -> Void) -> Void { var bodyString = "" var separator = "" let bodyData:NSMutableData = NSMutableData() let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) let finalEndpointURL = self.APIBaseURL + self.APIUrlSeparator + (!self.APIVersion.isEmpty ? self.APIVersion + self.APIUrlSeparator : "") + toEndpoint if self.APILogging { print("[APImatic] Sending POST request to URL: \(finalEndpointURL)") } let URL = NSURL(string: finalEndpointURL) let request = NSMutableURLRequest(URL: URL!) request.HTTPMethod = Methods.POST.rawValue if let callHeaders = withHeaders { for(key, val) in callHeaders { request.addValue("\(val)", forHTTPHeaderField: "\(key)") } } if let callParams = andParameters { for(paramKey, paramVal) in callParams { bodyString = "\(separator)--\(self.APImaticBoundary)\r\nContent-Disposition: form-data; name=\"\(paramKey)\"\r\n\r\n\(paramVal)" separator = "\r\n" bodyData.appendData(bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) } } if let callFilePath = withFilePath, let callFileName = andFileName, let callFileContentType = andFileContentType { let fileData = NSData(contentsOfFile: callFilePath) bodyString = "\(separator)--\(self.APImaticBoundary)\r\nContent-Disposition: form-data; name=\"payload\"; filename=\"\(callFileName)\"\r\nContent-Type: \(callFileContentType.rawValue)\r\n\r\n" separator = "\r\n" bodyData.appendData(bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) bodyData.appendData(fileData!) bodyData.appendData(separator.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) } bodyString = "--\(self.APImaticBoundary)--\r\n" bodyData.appendData(bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) request.HTTPBody = bodyData let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData?, response : NSURLResponse?, error : NSError?) -> Void in if let finalResponse = response { self.lastStatusCode = (finalResponse as! NSHTTPURLResponse).statusCode self.lastResponse = finalResponse } else { self.lastStatusCode = 0 self.lastResponse = nil } if let finalData = data { self.lastData = finalData } else { self.lastData = nil } if let finalError = error { self.lastError = finalError } else { self.lastError = nil } switch(self.lastStatusCode) { case 200, 201, 204, 304: withSuccessHandler(responseData: self.lastData, responseCode: self.lastStatusCode) break default: andFailureHandler(responseData: self.lastData, responseCode: self.lastStatusCode, responseError: self.lastError) } }) task.resume() } // MARK: - // MARK: Private methods private func NSURLByAppendingQueryParameters(URL:NSURL, queryParameters:Dictionary<String, String>) -> NSURL { let absoluteURLString = URL.absoluteString let queryParamtersString = self.stringFromQueryParameters(queryParameters) let URLString = absoluteURLString + "?" + queryParamtersString return NSURL(string: URLString)! } private func stringFromQueryParameters(queryParameters:Dictionary<String, String>) -> String { var parts:[String] = [] for (name, value) in queryParameters { if let paramName = name.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet()), let paramValue = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet()) { let part = "\(paramName)=\(paramValue)" parts.append(part as String) } } return parts.joinWithSeparator("&") } }
mit
acbe958be766aceee4dd4d64429bc2e8
44.201835
261
0.571342
5.199085
false
false
false
false
OneSadCookie/WebGLGame
tilepacker.swift
1
3952
#!/usr/bin/xcrun swift import Cocoa extension NSDirectoryEnumerator : SequenceType, GeneratorType { public typealias GeneratorType = NSDirectoryEnumerator public func generate() -> GeneratorType { return self } public typealias Element = NSString public func next() -> Element? { return nextObject() as? Element } } extension NSOutputStream : OutputStreamType { public func write(string: String) { string.withCString() { [weak self] (s: UnsafePointer<Int8>) -> () in let bytes = UnsafePointer<UInt8>(s) let len = Int(strlen(s)) self!.write(bytes, maxLength: len) } } } struct TileFile { let path: String let image: NSBitmapImageRep } var err:NSError? let dir = String.fromCString(C_ARGV[1])! let out_tiff = String.fromCString(C_ARGV[2])! let out_json = String.fromCString(C_ARGV[3])! let fm = NSFileManager.defaultManager() let png_re = NSRegularExpression(pattern: "^(.*)\\.png$", options: nil, error: &err) var images:Dictionary<String, TileFile> = [:] for filename in fm.enumeratorAtPath(dir)! { let string_range = NSRange(location: 0, length: filename.length) let match:NSTextCheckingResult? = png_re.firstMatchInString(filename, options: nil, range: string_range) if let m = match { let path = dir.stringByAppendingPathComponent(filename) images[filename.substringWithRange(m.rangeAtIndex(1))] = TileFile(path: path, image: NSBitmapImageRep(data: NSData(contentsOfFile: path))) } } var tile_size: (Int, Int)? for (k, v) in images { if let (w, h) = tile_size { if w != v.image.pixelsWide || h != v.image.pixelsHigh { println("Image \(k) is wrong size(\(v.image.pixelsWide) × \(v.image.pixelsHigh)); discarding.") images.removeValueForKey(k) } } else { tile_size = (v.image.pixelsWide, v.image.pixelsHigh) } // discard DPI v.image.size = NSSize(width: v.image.pixelsWide, height: v.image.pixelsHigh) } assert(tile_size != nil) let PAD = 2 let s = sqrt(Double(images.count)) let (tile_width, tile_height) = tile_size! var tiles_across = Int(ceil(s)) var tiles_down = Int(floor(s)) var total_tiles = tiles_across * tiles_down var pixel_width = tiles_across * (tile_width + PAD) + PAD var pixel_height = tiles_down * (tile_height + PAD) + PAD while total_tiles < images.count || pixel_width < pixel_height { if total_tiles < images.count { tiles_across += 1 } else if pixel_width < pixel_height { tiles_across += 1 tiles_down -= 1 } total_tiles = tiles_across * tiles_down pixel_width = tiles_across * (tile_width + PAD) + PAD pixel_height = tiles_down * (tile_height + PAD) + PAD } println("Using \(tiles_across) × \(tiles_down); \(total_tiles) total (\(images.count) filled); \(pixel_width)px × \(pixel_height)px") let large_image_rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: pixel_width, pixelsHigh: pixel_height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: pixel_width * 4, bitsPerPixel: 32) NSGraphicsContext.setCurrentContext(NSGraphicsContext(bitmapImageRep: large_image_rep)) var x = 0, y = 0 var json:NSMutableDictionary = [:] for (k, v) in images { let x_px = x * (tile_width + PAD) + PAD let y_px = y * (tile_height + PAD) + PAD v.image.drawAtPoint(NSPoint(x: x_px, y: y_px)) x += 1 if x >= tiles_across { x = 0 y += 1 } json[k] = [ "x": x_px, "y": y_px, "w": tile_width, "h": tile_height, ] } let json_data = NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted, error: &err)! json_data.writeToFile(out_json, atomically: true) NSGraphicsContext.currentContext().flushGraphics() large_image_rep.TIFFRepresentation.writeToFile(out_tiff + ".tiff", atomically: true)
mit
da61fee660ee667f8938b4aab11a0346
31.368852
270
0.655609
3.619615
false
false
false
false
net-a-porter-mobile/XCTest-Gherkin
Pod/Core/Example.swift
1
5001
// // Example.swift // whats-new // // Created by Sam Dean on 04/11/2015. // Copyright © 2015 net-a-porter. All rights reserved. // import Foundation import XCTest // Yep, turns out that an example is just a dictionary :) typealias ExampleTitle = String typealias ExampleValue = ExampleStringRepresentable /** An Example represents a single row in the Examples(...) block in a test */ typealias Example = [ExampleTitle: ExampleValue] public typealias ExampleStringRepresentable = MatchedStringRepresentable public extension XCTestCase { /** Supply a set of example data to the test. This must be done before calling `Outline`. If you specify a set of examples but don't run the test inside an `Outline { }` block then it won't do anything! - parameter titles: The titles for each column; these are the keys used to replace the placeholders in each step - parameter allValues: This is an array of columns - each array will be used as a single test */ func Examples(_ titles: [String], _ allValues: [ExampleStringRepresentable]...) { var all = [titles] let values = allValues.map { $0.map { String(describing: $0) } } all.append(contentsOf: values) Examples(all) } @nonobjc func Examples(_ values: [[String: ExampleStringRepresentable]]) { var titles = [String]() var allValues = [[ExampleStringRepresentable]](repeating: [], count: values.count) values.enumerated().forEach { (example) in example.element.sorted(by: { $0.key < $1.key }).forEach({ if !titles.contains($0.key) { titles.append($0.key) } allValues[example.offset] = allValues[example.offset] + [$0.value] }) } Examples([titles] + allValues) } /** If you want to reuse examples between tests then you can just pass in an array of examples directly. let examples = [ [ "title", "age" ], [ "a", "20" ], [ "b", "25" ] ] ... Examples(examples) */ func Examples(_ values: [[ExampleStringRepresentable]]) { precondition(values.count > 1, "You must pass at least one set of example data") // Split out the titles and the example data let titles = values.first! let allValues = values.dropFirst() // TODO: Hints at a reduce, but we're going over two arrays at once . . . :| var accumulator = Array<Example>() allValues.forEach { values in precondition(values.count == titles.count, "Each example must be the same size as the titles (was \(values.count), expected \(titles.count))") // Loop over both titles and values, creating a dictionary (i.e. an Example) var example = Example() (0..<titles.count).forEach { n in let title = String(describing: titles[n]) let value = String(describing: values[n]) example[title] = value } accumulator.append(example) } state.examples = accumulator } /** Run the following steps as part of an outline - this will replace any placeholders with each example in turn. You must have setup the example cases before calling this; use `Example(...)` to do this. - parameter routine: A block containing your Given/When/Then which will be run once per example */ func Outline(_ routine: ()->()) { precondition(state.examples != nil, "You need to define examples before running an Outline block - use Examples(...)"); precondition(state.examples!.count > 0, "You've called Examples but haven't passed anything in. Nice try.") state.examples!.forEach { example in state.currentExample = example self.performBackground() routine() state.currentExample = nil } } func Outline(_ routine: ()->(), examples titles: [String], _ allValues: [String]...) { Outline(routine, examples: [titles] + allValues) } func Outline(_ routine: ()->(), _ allValues: () -> [[String]]) { Outline(routine, examples: allValues()) } func Outline(_ routine: ()->(), examples allValues: [[String]]) { Examples(allValues) Outline(routine) } func Outline(_ routine: ()->(), _ allValues: () -> [[String: ExampleStringRepresentable]]) { Outline(routine, examples: allValues()) } func Outline(_ routine: ()->(), examples allValues: [[String: ExampleStringRepresentable]]) { Examples(allValues) Outline(routine) } func exampleValue<T: ExampleStringRepresentable>(_ title: String) -> T? { let value = state.currentExample?[title] if let value = value as? T { return value } else if let value = value as? String { return T(fromMatch: value) } return nil } }
apache-2.0
9c7ec910e375c9c4d0809bbfbe1079b9
33.013605
154
0.6072
4.638219
false
false
false
false
courteouselk/Relations
Tests/RelationsTests/KeyedWeakNaryTests+Folder.swift
1
2179
// // KeyedWeakNaryTests+Folder.swift // Relations // // Created by Anton Bronnikov on 07/03/2017. // Copyright © 2017 Anton Bronnikov. All rights reserved. // import Relations extension KeyedWeakNaryTests { final class Folder : Equatable, CustomStringConvertible { static func == (lhs: Folder, rhs: Folder) -> Bool { return lhs === rhs } var description: String { return name } let name: String private (set) var _files: KeyedWeak1toNRelation<Folder, File, String>! = nil var files: [File] { get { return _files.sorted(by: { $0.name < $1.name }) } set { _files.assign(relations: newValue) } } var anyFile: File? { return _files.first } var count: Int { return _files.count } var underestimatedCount: Int { return _files.underestimatedCount } var fileNames: [String] { return _files.keys.sorted() } var notificationsCount = 0 var filenamesOnLastestNotification: [String] = [] private func filesDidChange() { notificationsCount += 1 filenamesOnLastestNotification = files.map({ $0.name }) } init(name: String) { self.name = name _files = KeyedWeak1toNRelation(this: self, getCounterpart: { $0._folder }, didChange: { [unowned self] in self.filesDidChange() }) } func insert(file: File?) { _files.insert(relation: file) } func insert(files: [File]) { _files.insert(relations: files) } func remove(file: File?) { _files.remove(relation: file) } func remove(filename: String?) { _files.remove(key: filename) } func remove(files: [File]) { _files.remove(relations: files) } func remove(filenames: [String]) { _files.remove(keys: filenames) } func removeAll() { _files.flush() } func getFile(withName name: String) -> File? { return _files.lookup(key: name) } } }
mit
6fdf68b855f0fb483ab93dab3c470ed5
23.75
142
0.546373
4.364729
false
false
false
false
lionchina/RxSwiftBook
RxTableViewWithEdit/RxTableViewWithEdit/AppDelegate.swift
1
4617
// // AppDelegate.swift // RxTableViewWithEdit // // Created by MaxChen on 05/08/2017. // Copyright © 2017 com.linglustudio. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "RxTableViewWithEdit") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
187ffa0f70512309aba8e84a89cfe384
48.634409
285
0.687608
5.843038
false
false
false
false
brentsimmons/Evergreen
Shared/HTMLMetadata/HTMLMetadataDownloader.swift
1
1180
// // HTMLMetadataDownloader.swift // NetNewsWire // // Created by Brent Simmons on 11/26/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation import RSWeb import RSParser struct HTMLMetadataDownloader { static let serialDispatchQueue = DispatchQueue(label: "HTMLMetadataDownloader") static func downloadMetadata(for url: String, _ completion: @escaping (RSHTMLMetadata?) -> Void) { guard let actualURL = URL(unicodeString: url) else { completion(nil) return } downloadUsingCache(actualURL) { (data, response, error) in if let data = data, !data.isEmpty, let response = response, response.statusIsOK, error == nil { let urlToUse = response.url ?? actualURL let parserData = ParserData(url: urlToUse.absoluteString, data: data) parseMetadata(with: parserData, completion) return } completion(nil) } } private static func parseMetadata(with parserData: ParserData, _ completion: @escaping (RSHTMLMetadata?) -> Void) { serialDispatchQueue.async { let htmlMetadata = RSHTMLMetadataParser.htmlMetadata(with: parserData) DispatchQueue.main.async { completion(htmlMetadata) } } } }
mit
0aa9f35d017f3ec139b1ecdcfb9483f2
26.418605
116
0.729432
3.731013
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01052-swift-genericsignature-get.swift
11
1007
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse extension Array { typealias R = a<T.Element>(Any) { return self.Iterator..E == "](((b(bytes: S<T : C> a { extension NSData { struct e { } func d: (2, y: NSObject { } func f() -> Any { public var e> { } return g: Any, AnyObject) -> { } } struct c { }("""foo") func e> T -> Any) -> { } return { _, AnyObject)-> String { A? = b: a { } } } for (A>) -> { extension String { typealias e == { c<T { class A>) -> A : T, x } } } protocol a { extension NSData { } } typealias A { protocol A { static let v: b = b({ } i<T>, "") } } } let h : A where T, AnyObject.A, f(n: AnyObject) -> { typealias B == true } } func d<b: d wh
apache-2.0
22aee9bf18d193d50ff8ef5ae49b65cc
18
78
0.624628
2.910405
false
false
false
false
YMonnier/ProBill
ProBill/ProBill/Controller/Bills/BillsViewController.swift
1
7333
// // BillsViewController.swift // ProBill // // Created by Ysée Monnier on 29/04/16. // Copyright © 2016 MONNIER Ysee. All rights reserved. // import UIKit import CoreData class BillsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UISearchBarDelegate { //CollectionView @IBOutlet weak var collectionView: UICollectionView! let reuseIdentifierCell = "BillCell" let reuseIdentifierHeader = "BillHeader" @IBOutlet weak var searchBar: UISearchBar! var managedObjectContext: NSManagedObjectContext? = nil var billSegue: Bill? = nil //Data var data: [SubCategory] = [] { didSet { self.collectionView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext //register nib view self.collectionView!.register(UINib(nibName: "BillCell", bundle: Bundle(for: BillsViewController.self )), forCellWithReuseIdentifier: reuseIdentifierCell) self.collectionView!.register(UINib(nibName: "BillHeader", bundle: Bundle(for: BillsViewController.self )), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseIdentifierHeader) //Load data... self.loadData() //Layout creation let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 1 layout.minimumLineSpacing = 1 layout.headerReferenceSize = CGSize(width: 100,height: 60) self.collectionView.collectionViewLayout = layout self.automaticallyAdjustsScrollViewInsets = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { self.loadData() self.collectionView.reloadData() } //MARK:- Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { print(#function) if segue.identifier == "DetailSegue" { let destinationController = segue.destination as! BillDetailViewController destinationController.bill = self.billSegue } } //MARK: Action @IBAction func editAction(_ sender: AnyObject) { } //MARK: - UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { print(#function) print(self.data.count) return self.data.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { print(#function) print(self.data[section].bills.count) return self.data[section].bills.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifierCell, for: indexPath) as! BillCellView let bill: Bill = Array(self.data[indexPath.section].bills)[indexPath.row] //cell.backgroundColor = UIColor.clearColor() cell.picture.image = UIImage(data: (bill.pictures.first?.image)! as Data) cell.price.text = String(bill.price) + " Zl" cell.date.text = bill.date.toString("yyyy-MM-dd") return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.billSegue = Array(self.data[indexPath.section].bills)[indexPath.row] self.performSegue(withIdentifier: "DetailSegue", sender: self) self.searchBar.showsCancelButton = false self.searchBar.resignFirstResponder() self.searchBar.text = "" } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let rect = UIScreen.main.bounds let screenWidth = rect.size.width - 40 return CGSize(width: screenWidth/3, height: 160); } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader && !self.data[indexPath.section].bills.isEmpty { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseIdentifierHeader, for: indexPath) as! BillHeaderView header.title.text = self.data[(indexPath as NSIndexPath).section].name return header; } return UICollectionReusableView() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(10, 5, 10, 5); //top,left,bottom,right } //MARK: - Search control func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { print(#function) autoreleasepool { var predicate: NSPredicate? = nil var error: NSError? = nil var result: [AnyObject]? if self.searchBar.text?.characters.count != 0 { predicate = NSPredicate(format: "(name contains [cd] %@)", searchBar.text!) } let fetch = NSFetchRequest<SubCategory>(entityName: "SubCategory") fetch.predicate = predicate do { result = try self.managedObjectContext!.fetch(fetch) } catch let nserror1 as NSError{ error = nserror1 result = nil } if result != nil { self.data = [] self.data = (result as! [SubCategory]).filter({ (sc) -> Bool in !sc.bills.isEmpty }) } } } // called when cancel button pressed func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { print(#function) self.searchBar.showsCancelButton = false self.searchBar.resignFirstResponder() self.searchBar.text = "" self.loadData() } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { self.searchBar.showsCancelButton = true return true } //MARK: - LoadData fileprivate func loadData() { autoreleasepool { var error: NSError? = nil var result: [AnyObject]? let fetch = NSFetchRequest<SubCategory>(entityName: "SubCategory") do { result = try self.managedObjectContext!.fetch(fetch) } catch let nserror1 as NSError{ error = nserror1 result = nil } if result != nil { self.data = [] self.data = (result as! [SubCategory]).filter({ (sc) -> Bool in !sc.bills.isEmpty }) } } } }
mit
09c7879f4eb93ff7ce31eabbe5c1a731
34.936275
225
0.629109
5.574905
false
false
false
false
mikewitney/Bluefruit_LE_Connect
BLE Test/HelpViewController.swift
2
2178
// // HelpViewController.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 10/6/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import Foundation import UIKit @objc protocol HelpViewControllerDelegate : Any{ func helpViewControllerDidFinish(controller : HelpViewController) } class HelpViewController : UIViewController { @IBOutlet var delegate : HelpViewControllerDelegate? @IBOutlet var versionLabel : UILabel? @IBOutlet var textView : UITextView? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // override init() { // super.init() // } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) preferredContentSize = CGSizeMake(320.0, 480.0) //popover size on iPad } override func viewDidLoad() { super.viewDidLoad() if (IS_IPAD == true) { self.preferredContentSize = self.view.frame.size; //popover size on iPad } else if (IS_IPHONE == true) { self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal } //Set the app version # in the Help/Info view let versionString: String = "v" + ((NSBundle.mainBundle().infoDictionary)?["CFBundleShortVersionString"] as! String!) // let bundleVersionString: String = "b" + ((NSBundle.mainBundle().infoDictionary)?["CFBundleVersion"] as String!) // Build number // versionLabel?.text = versionString + " " + bundleVersionString versionLabel?.text = versionString } override func viewDidAppear(animated : Bool){ super.viewDidAppear(animated) textView?.flashScrollIndicators() //indicate add'l content below screen } @IBAction func done(sender : AnyObject) { delegate?.helpViewControllerDidFinish(self) } }
bsd-3-clause
7cc8cf11c5c094955c2687b283282cd1
24.337209
147
0.604224
5.312195
false
false
false
false
HongliYu/DPSlideMenuKit-Swift
DPSlideMenuKitDemo/SideContent/DPChannelListViewController.swift
1
8998
// // DPChannelListViewController.swift // DPSlideMenuKitDemo // // Created by Hongli Yu on 04/07/2017. // Copyright © 2017 Hongli Yu. All rights reserved. // import UIKit let kDPChannelListCellReuseID: String = "kDPChannelListCellReuseID" let kDefaultCellHeight: CGFloat = 44.0 let kDefaultSectionHeight: CGFloat = 44.0 class DPChannelListViewController: DPBaseEmbedViewController { @IBOutlet weak var mainTableView: UITableView! private(set) var channelViewModels: [DPChannelViewModel] = [] private var addChannelAction:(()->Void)? @IBOutlet weak var teamIconImageView: UIImageView! { didSet { teamIconImageView.layoutIfNeeded() teamIconImageView.layer.cornerRadius = 5 teamIconImageView.layer.masksToBounds = true } } @IBOutlet weak var titleContentViewTopConstraints: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() basicUI() basicData() } func basicUI() { mainTableView.register(UITableViewCell.self, forCellReuseIdentifier: kDPChannelListCellReuseID) mainTableView.separatorStyle = .none mainTableView.backgroundColor = UIColor.clear mainTableView.delegate = self mainTableView.dataSource = self if UIScreen().iPhoneBangsScreen { titleContentViewTopConstraints.constant = 20 } } func basicData() { let channelCellViewModel = DPChannelCellViewModel(color: UIColor.clear, title: "# All Threads", cellHeight: kDefaultCellHeight) { [weak self] in guard let strongSelf = self else { return } strongSelf.alert("All Thread Action! Function: \(#function), line: \(#line)") } let channelSectionViewModel = DPChannelSectionViewModel(title: "", height: kDefaultSectionHeight) { [weak self] in guard let strongSelf = self else { return } strongSelf.alert("Section Action! Function: \(#function), line: \(#line)") } let channelViewModel0: DPChannelViewModel = DPChannelViewModel(channelCellViewModels: [channelCellViewModel], channelSectionViewModel: channelSectionViewModel) channelViewModels.append(channelViewModel0) let channelCellViewModel0 = DPChannelCellViewModel(color: Palette.main, title: "# awesome channel 0", cellHeight: kDefaultCellHeight) { [weak self] in guard let strongSelf = self else { return } if let viewController = UIViewController.viewController(DPChatViewController.self, storyboard: "Pages") as? DPChatViewController { DPSlideMenuManager.shared.replaceCenter(viewController, position: strongSelf.positionState) viewController.bindData(title: "channel 0", message: "this is awesome channel 0") } } let channelSectionViewModel0 = DPChannelSectionViewModel(title: "CHANNELS", height: kDefaultSectionHeight) { [weak self] in guard let strongSelf = self else { return } strongSelf.alert("CHANNELS Section Action! Function: \(#function), line: \(#line)") } let channelCellViewModel1 = DPChannelCellViewModel(color: Palette.blue, title: "# awesome channel 1", cellHeight: kDefaultCellHeight) { [weak self] in guard let strongSelf = self else { return } if let viewController = UIViewController.viewController(DPChatViewController.self, storyboard: "Pages") as? DPChatViewController { DPSlideMenuManager.shared.replaceCenter(viewController, position: strongSelf.positionState) viewController.bindData(title: "channel 1", message: "this is awesome channel 1") } } let channelCellViewModel2 = DPChannelCellViewModel(color: UIColor.random(), title: "# Rate", cellHeight: kDefaultCellHeight) { let urlString: String = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=910117892" // replace 910117892 with your appid UIApplication.shared.open(URL(string: urlString)!, options: [:], completionHandler: nil) } let channelCellViewModel3 = DPChannelCellViewModel(color: UIColor.random(), title: "# Donate", cellHeight: kDefaultCellHeight) { let targetURL: String = "https://qr.alipay.com/apeez0tpttrt2yove2" UIApplication.shared.open(URL(string: targetURL)!, options: [:], completionHandler: nil) // Donate with alipay } let channelViewModel1: DPChannelViewModel = DPChannelViewModel( channelCellViewModels: [channelCellViewModel0, channelCellViewModel1, channelCellViewModel2, channelCellViewModel3], channelSectionViewModel: channelSectionViewModel0) channelViewModels.append(channelViewModel1) } func updateUI() { mainTableView.reloadData() } } extension DPChannelListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return channelViewModels.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { for (index, channelViewModel) in channelViewModels.enumerated() { if section == index { return channelViewModel.channelCellViewModels?.count ?? 0 } } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kDPChannelListCellReuseID, for: indexPath) let channelViewModel: DPChannelViewModel? = channelViewModels[indexPath.section] let channelCellViewModel: DPChannelCellViewModel? = channelViewModel?.channelCellViewModels?[indexPath.row] cell.textLabel?.text = channelCellViewModel?.title?.localized cell.textLabel?.textColor = UIColor.white cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 20.0) cell.backgroundColor = channelCellViewModel?.color return cell } } extension DPChannelListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 1 ? kDefaultSectionHeight : 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard section == 1 else { return nil} let channelViewModel: DPChannelViewModel? = channelViewModels[section] addChannelAction = channelViewModel?.channelSectionViewModel?.actionBlock let view = UIView(frame: CGRect(x:0, y:0, width:UIScreen.main.bounds.width, height:20)) view.backgroundColor = UIColor.clear let label = UILabel(frame: CGRect(x:16, y:0, width:200, height:kDefaultSectionHeight)) label.font = UIFont.systemFont(ofSize: 16) label.text = channelViewModel?.channelSectionViewModel?.title label.textColor = UIColor.white label.backgroundColor = UIColor.clear view.addSubview(label) let addChannelButton: UIButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.width + kDPDrawerControllerLeftViewInitialOffset - kDefaultSectionHeight, y: 0, width: kDefaultSectionHeight, height: kDefaultSectionHeight)) addChannelButton.backgroundColor = UIColor.clear addChannelButton.titleLabel!.font = UIFont(name: "fontawesome", size: 24)! addChannelButton.setTitle("\u{f055}", for: .normal) addChannelButton.setTitleColor(UIColor.white, for: .normal) addChannelButton.addTarget(self, action: #selector(self.addChannelAction(_:)), for: .touchUpInside) view.addSubview(addChannelButton) return view } @objc func addChannelAction(_ sender: UIButton) { addChannelAction?() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let channelViewModel: DPChannelViewModel? = channelViewModels[indexPath.section] let channelCellViewModel: DPChannelCellViewModel? = channelViewModel?.channelCellViewModels?[indexPath.row] return channelCellViewModel?.cellHeight ?? kDefaultCellHeight } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let channelViewModel: DPChannelViewModel? = channelViewModels[indexPath.section] let channelCellViewModel: DPChannelCellViewModel? = channelViewModel?.channelCellViewModels?[indexPath.row] channelCellViewModel?.actionBlock?() } }
mit
2a61a7f05068eee7b0b8b3b94cf145d5
42.674757
149
0.673224
5.58473
false
false
false
false
KYawn/myiOS
myScrowllView/myScrowllView/ViewController.swift
1
2214
// // ViewController.swift // myScrowllView // // Created by K.Yawn Xoan on 3/22/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit class ViewController: UIViewController,UIScrollViewDelegate { @IBOutlet weak var pageControl1: UIPageControl! @IBOutlet weak var scrollView1: UIScrollView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. scrollView1.backgroundColor = UIColor.redColor() scrollView1.contentSize = CGSize(width: 320*4, height: 568) scrollView1.indicatorStyle = UIScrollViewIndicatorStyle.White scrollView1.delegate = self var aView = UIView(frame: CGRect(x: 0*320, y: 0, width: 320, height: 568)) aView.backgroundColor = UIColor.yellowColor() scrollView1.addSubview(aView) var bView = UIView(frame: CGRect(x: 1*320, y: 0, width: 320, height: 568)) bView.backgroundColor = UIColor.greenColor() scrollView1.addSubview(bView) var cView = UIView(frame: CGRect(x: 2*320, y: 0, width: 320, height: 568)) cView.backgroundColor = UIColor.blueColor() scrollView1.addSubview(cView) var dView = UIView(frame: CGRect(x: 3*320, y: 0, width: 320, height: 568)) dView.backgroundColor = UIColor.blackColor() scrollView1.addSubview(dView) pageControl1.addTarget(self, action: "pageChanged", forControlEvents: UIControlEvents.ValueChanged) } func pageChanged(){ var curPage = pageControl1.currentPage scrollView1.scrollRectToVisible(CGRect(x: curPage*320, y: 0, width: 320, height: 568), animated: true) } func scrollViewDidScroll(scrollView: UIScrollView) { //让pageControl 跟着变动,要计算当前偏移量 var curPage = scrollView.contentOffset.x/320 //pageControl 设定当前页 pageControl1.currentPage = Int(curPage) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
da630519244858aa988276199c1773d0
33
110
0.651654
4.486598
false
false
false
false
1170197998/SinaWeibo
SFWeiBo/SFWeiBo/Classes/Home/StatusTableViewCell.swift
1
3791
// // StatusTableViewCell.swift // SFWeiBo // // Created by mac on 16/4/20. // Copyright © 2016年 ShaoFeng. All rights reserved. // import UIKit import SDWebImage //用于显示图片的collectionView的cell重用标识 let SFPictureCellReuseIdentifier = "SFPictureCellReuseIdentifier" //保存cell的重用标识 enum StatusTableViewCellIdentifier: String { //前面的枚举值,后面的是原始值 case NormalCell = "NormalCell" case ForwardCell = "ForwardCell" //在枚举中使用status修饰方法,相当于类中的class方法 //调用枚举的rawValue,相当于拿到枚举的原始值 //根据模型判断是哪个cell static func cellID(status: Status) -> String { return status.retweeted_status != nil ? ForwardCell.rawValue : NormalCell.rawValue } } class StatusTableViewCell: UITableViewCell { //保存配图的宽高约束 var pictureWidthCons: NSLayoutConstraint? var pictureHeightCons: NSLayoutConstraint? var pictureTopCons: NSLayoutConstraint? var status: Status? { didSet{ //设置顶部视图数据 topView.status = status //设置正文 contentLabel.text = status?.text //设置配图尺寸 pictureView.status = status?.retweeted_status != nil ? status?.retweeted_status : status //根据模型计算配图尺寸,先传递模型,后计算 let size = pictureView.calculateImageSize() //设置配图尺寸 pictureWidthCons?.constant = size.width pictureHeightCons?.constant = size.height pictureTopCons?.constant = size.height == 0 ? 0 : 10 } } // 自定义一个类需要重写的init方法是 designated override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // 初始化UI setupUI() } func setupUI() { // 1.添加子控件 contentView.addSubview(topView) contentView.addSubview(contentLabel) contentView.addSubview(pictureView) contentView.addSubview(footerView) let width = UIScreen.mainScreen().bounds.width // 2.布局子控件 topView.AlignInner(type: AlignType.TopLeft, referView: contentView, size: CGSizeMake(width, 60)) contentLabel.AlignVertical(type: AlignType.BottomLeft, referView: topView, size: nil, offset: CGPoint(x: 10, y: 10)) footerView.AlignVertical(type: AlignType.BottomLeft, referView: pictureView, size: CGSize(width: width, height: 44), offset: CGPoint(x: -10, y: 10)) } //用于获取行高 func rowHeight(status: Status) -> CGFloat { //为了能够调用didSet,计算配图的高度 self.status = status //强制更新UI self.layoutIfNeeded() //返回底部视图最大的Y值 return CGRectGetMaxY(footerView.frame) } // MARK: - 懒加载 //顶部视图 private lazy var topView: StatusTableViewTopView = StatusTableViewTopView() /// 正文 lazy var contentLabel: UILabel = { let label = UILabel.creatLabel(UIColor.darkGrayColor(), fontSize: 15) label.numberOfLines = 0 //设置最大宽度 label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 20 return label }() ///配图 lazy var pictureView: StatusPictureView = StatusPictureView() /// 底部工具条 lazy var footerView: StatusTableViewBottomView = StatusTableViewBottomView() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
27fdb2ae6ffd6a213744cf6bdeed2946
29.87156
156
0.643579
4.646409
false
false
false
false
red-spotted-newts-2014/rest-less-ios
Rest Less/SecondViewController.swift
1
2673
// // SecondViewController.swift // Rest Less // // Created by Apprentice on 8/16/14. // Copyright (c) 2014 newts. All rights reserved. // import UIKit class SecondViewController: UIViewController, APIGetWorkoutControllerProtocol { var workoutTimer = NSTimer() var accumulatedTime = 0.0 var startTimeDate: NSDate! @IBOutlet weak var displayWorkoutLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeRight.direction = UISwipeGestureRecognizerDirection.Right // Do any additional setup after loading the view. } @IBAction func startWorkout (sender: AnyObject) { if workoutTimer.valid != true { let aSelector : Selector = "sumWorkoutTime" startTimeDate = NSDate(timeIntervalSinceReferenceDate: NSDate.timeIntervalSinceReferenceDate()) workoutTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true) } } @IBAction func stopWorkoutTime (sender: AnyObject) { workoutTimer.invalidate() } func respondToSwipeGesture(gesture: UIGestureRecognizer) { if let swipeGesture = gesture as? UISwipeGestureRecognizer { switch swipeGesture.direction { case UISwipeGestureRecognizerDirection.Right: println("Swiped right") default: break } } } @IBAction func getData(sender: AnyObject) { var api = APIGetWorkoutController() var url = "http://secret-stream-5880.herokuapp.com" var workout_id = "1" api.delegate = self api.HTTPGetter(url + "/" + workout_id + ".json") } var response:NSDictionary? func receivedGetResponse(result: NSDictionary) -> NSDictionary { println(result) return result } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func sumWorkoutTime() { accumulatedTime += workoutTimer.timeInterval } /* // 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
ac2de3e8812ec1f37e5f6eaea310c429
28.054348
132
0.642724
5.272189
false
false
false
false
jianghongbing/APIReferenceDemo
UIKit/UISearchController/UISearchController/ResultTableViewController.swift
1
1659
// // ResultTableViewController.swift // UISearchController // // Created by pantosoft on 2017/6/19. // Copyright © 2017年 jianghongbing. All rights reserved. // import UIKit @objc protocol ResultTableViewControllerDelegate { @objc optional func resultTableViewController(resultTableViewController: ResultTableViewController,didSelectedItem item: Item) } class ResultTableViewController: UITableViewController { var items = [Item]() let cellIdentifier = "resultTableViewCell" weak var delegate: ResultTableViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = .init(rawValue: 0) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) let item = items[indexPath.row] cell.textLabel?.text = item.itemNumber cell.detailTextLabel?.text = "price:\(item.itemPrice)" return cell } // MARK: - table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if delegate != nil && ((delegate?.resultTableViewController) != nil) { delegate!.resultTableViewController!(resultTableViewController: self, didSelectedItem: items[indexPath.row]) } } }
mit
44afc93f083683d6a1bdcac8f1899b2a
33.5
130
0.707126
5.223975
false
false
false
false
stephanecopin/ObjectMapper
ObjectMapperTests/ObjectMapperTests.swift
3
18255
// // ObjectMapperTests.swift // ObjectMapperTests // // Created by Tristan Himmelman on 2014-10-16. // Copyright (c) 2014 hearst. All rights reserved. // import Foundation import XCTest import ObjectMapper import Nimble class ObjectMapperTests: XCTestCase { let userMapper = Mapper<User>() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testBasicParsing() { let username = "John Doe" let identifier = "user8723" let photoCount = 13 let age = 1227 let weight = 123.23 let float: Float = 123.231 let drinker = true let smoker = false let sex: Sex = .Female let arr = [ "bla", true, 42 ] let directory = [ "key1" : "value1", "key2" : false, "key3" : 142 ] let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"username\" : \"sub user\" }" let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"sex\":\"\(sex.rawValue)\", \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" let user = userMapper.map(userJSONString)! expect(user).notTo(beNil()) expect(username).to(equal(user.username)) expect(identifier).to(equal(user.identifier)) expect(photoCount).to(equal(user.photoCount)) expect(age).to(equal(user.age)) expect(weight).to(equal(user.weight)) expect(float).to(equal(user.float)) expect(drinker).to(equal(user.drinker)) expect(smoker).to(equal(user.smoker)) expect(sex).to(equal(user.sex)) //println(Mapper().toJSONString(user, prettyPrint: true)) } func testInstanceParsing() { let username = "John Doe" let identifier = "user8723" let photoCount = 13 let age = 1227 let weight = 123.23 let float: Float = 123.231 let drinker = true let smoker = false let sex: Sex = .Female let arr = [ "bla", true, 42 ] let directory = [ "key1" : "value1", "key2" : false, "key3" : 142 ] let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"username\" : \"sub user\" }" let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"sex\":\"\(sex.rawValue)\", \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 },\"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" let user = Mapper().map(userJSONString, toObject: User()) expect(username).to(equal(user.username)) expect(identifier).to(equal(user.identifier)) expect(photoCount).to(equal(user.photoCount)) expect(age).to(equal(user.age)) expect(weight).to(equal(user.weight)) expect(float).to(equal(user.float)) expect(drinker).to(equal(user.drinker)) expect(smoker).to(equal(user.smoker)) expect(sex).to(equal(user.sex)) //println(Mapper().toJSONString(user, prettyPrint: true)) } func testDictionaryParsing() { var name: String = "Genghis khan" var UUID: String = "12345" var major: Int = 99 var minor: Int = 1 let json: [String: AnyObject] = ["name": name, "UUID": UUID, "major": major] //test that the sematics of value types works as expected. the resulting maped student //should have the correct minor property set even thoug it's not mapped var s = Student() s.minor = minor let student = Mapper().map(json, toObject: s) expect(student.name).to(equal(name)) expect(student.UUID).to(equal(UUID)) expect(student.major).to(equal(major)) expect(student.minor).to(equal(minor)) //Test that mapping a reference type works as expected while not relying on the return value var username: String = "Barack Obama" var identifier: String = "Political" var photoCount: Int = 1000000000 let json2: [String: AnyObject] = ["username": username, "identifier": identifier, "photoCount": photoCount] let user = User() Mapper().map(json2, toObject: user) expect(user.username).to(equal(username)) expect(user.identifier).to(equal(identifier)) expect(user.photoCount).to(equal(photoCount)) } func testNullObject() { let JSONString = "{\"username\":\"bob\"}" let user = userMapper.map(JSONString) expect(user).notTo(beNil()) expect(user?.age).to(beNil()) } func testToObjectFromString() { let username = "bob" let JSONString = "{\"username\":\"\(username)\"}" var user = User() user.username = "Tristan" Mapper().map(JSONString, toObject: user) expect(user.username).to(equal(username)) } func testToObjectFromJSON() { let username = "bob" let JSON = ["username": username] var user = User() user.username = "Tristan" Mapper().map(JSON, toObject: user) expect(user.username).to(equal(username)) } func testToObjectFromAnyObject() { let username = "bob" let userJSON = ["username": username] var user = User() user.username = "Tristan" Mapper().map(userJSON as AnyObject?, toObject: user) expect(user.username).to(equal(username)) } func testToJSONAndBack(){ var user = User() user.username = "tristan_him" user.identifier = "tristan_him_identifier" user.photoCount = 0 user.age = 28 user.weight = 150 user.drinker = true user.smoker = false user.sex = .Female user.arr = ["cheese", 11234] let JSONString = Mapper().toJSONString(user, prettyPrint: true) //println(JSONString) let parsedUser = userMapper.map(JSONString!)! expect(parsedUser).notTo(beNil()) expect(user.identifier).to(equal(parsedUser.identifier)) expect(user.photoCount).to(equal(parsedUser.photoCount)) expect(user.age).to(equal(parsedUser.age)) expect(user.weight).to(equal(parsedUser.weight)) expect(user.drinker).to(equal(parsedUser.drinker)) expect(user.smoker).to(equal(parsedUser.smoker)) expect(user.sex).to(equal(parsedUser.sex)) } func testUnknownPropertiesIgnored() { let JSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\", \"foo\" : \"bar\", \"fooArr\" : [ 1, 2, 3], \"fooObj\" : { \"baz\" : \"qux\" } }" let user = userMapper.map(JSONString) expect(user).notTo(beNil()) } func testInvalidJsonResultsInNilObject() { let JSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\"" // missing ending brace let user = userMapper.map(JSONString) expect(user).to(beNil()) } func testMapArrayJSON(){ let name1 = "Bob" let name2 = "Jane" let JSONString = "[{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123},{ \"name\": \"\(name2)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC876\", \"major\": 54321,\"minor\": 13 }]" let students = Mapper<Student>().mapArray(JSONString) expect(students).notTo(beEmpty()) expect(students.count).to(equal(2)) expect(students[0].name).to(equal(name1)) expect(students[1].name).to(equal(name2)) } // test mapArray() with JSON string that is not an array form // should return a collection with one item func testMapArrayJSONWithNoArray(){ let name1 = "Bob" let JSONString = "{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123}" let students = Mapper<Student>().mapArray(JSONString) expect(students).notTo(beEmpty()) expect(students.count).to(equal(1)) expect(students[0].name).to(equal(name1)) } func testArrayOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSONString = "{ \"tasks\": [{\"taskId\":103,\"percentage\":\(percentage1)},{\"taskId\":108,\"percentage\":\(percentage2)}] }" let plan = Mapper<Plan>().map(JSONString) let tasks = plan?.tasks expect(tasks).notTo(beNil()) expect(tasks?[0].percentage).to(equal(percentage1)) expect(tasks?[1].percentage).to(equal(percentage2)) } func testDictionaryOfArrayOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSONString = "{ \"dictionaryOfTasks\": { \"mondayTasks\" :[{\"taskId\":103,\"percentage\":\(percentage1)},{\"taskId\":108,\"percentage\":\(percentage2)}] } }" let plan = Mapper<Plan>().map(JSONString) let dictionaryOfTasks = plan?.dictionaryOfTasks expect(dictionaryOfTasks).notTo(beNil()) expect(dictionaryOfTasks?["mondayTasks"]?[0].percentage).to(equal(percentage1)) expect(dictionaryOfTasks?["mondayTasks"]?[1].percentage).to(equal(percentage2)) let planToJSON = Mapper().toJSONString(plan!, prettyPrint: false) //println(planToJSON) let planFromJSON = Mapper<Plan>().map(planToJSON!) let dictionaryOfTasks2 = planFromJSON?.dictionaryOfTasks expect(dictionaryOfTasks2).notTo(beNil()) expect(dictionaryOfTasks2?["mondayTasks"]?[0].percentage).to(equal(percentage1)) expect(dictionaryOfTasks2?["mondayTasks"]?[1].percentage).to(equal(percentage2)) } func testArrayOfEnumObjects(){ let a: ExampleEnum = .A let b: ExampleEnum = .B let c: ExampleEnum = .C let JSONString = "{ \"enums\": [\(a.rawValue), \(b.rawValue), \(c.rawValue)] }" let enumArray = Mapper<ExampleEnumArray>().map(JSONString) let enums = enumArray?.enums expect(enums).notTo(beNil()) expect(enums?.count).to(equal(3)) expect(enums?[0]).to(equal(a)) expect(enums?[1]).to(equal(b)) expect(enums?[2]).to(equal(c)) } func testDictionaryOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSONString = "{\"tasks\": { \"task1\": {\"taskId\":103,\"percentage\":\(percentage1)}, \"task2\": {\"taskId\":108,\"percentage\":\(percentage2)}}}" let taskDict = Mapper<TaskDictionary>().map(JSONString) let task = taskDict?.tasks?["task1"] expect(task).notTo(beNil()) expect(task?.percentage).to(equal(percentage1)) } func testDictionryOfEnumObjects(){ let a: ExampleEnum = .A let b: ExampleEnum = .B let c: ExampleEnum = .C let JSONString = "{ \"enums\": {\"A\": \(a.rawValue), \"B\": \(b.rawValue), \"C\": \(c.rawValue)} }" let enumDict = Mapper<ExampleEnumDictionary>().map(JSONString) let enums = enumDict?.enums expect(enums).notTo(beNil()) expect(enums?.count).to(equal(3)) } func testDoubleParsing(){ let percentage1: Double = 1792.41 let JSONString = "{\"taskId\":103,\"percentage\":\(percentage1)}" let task = Mapper<Task>().map(JSONString) expect(task).notTo(beNil()) expect(task?.percentage).to(equal(percentage1)) } func testMappingAGenericObject(){ let code: Int = 22 let JSONString = "{\"result\":{\"code\":\(code)}}" let response = Mapper<Response<Status>>().map(JSONString) let status = response?.result?.status expect(status).notTo(beNil()) expect(status).to(equal(code)) } func testToJSONArray(){ var task1 = Task() task1.taskId = 1 task1.percentage = 11.1 var task2 = Task() task2.taskId = 2 task2.percentage = 22.2 var task3 = Task() task3.taskId = 3 task3.percentage = 33.3 var taskArray = [task1, task2, task3] let JSONArray = Mapper().toJSONArray(taskArray) let taskId1 = JSONArray[0]["taskId"] as? Int let percentage1 = JSONArray[0]["percentage"] as? Double expect(taskId1).to(equal(task1.taskId)) expect(percentage1).to(equal(task1.percentage)) let taskId2 = JSONArray[1]["taskId"] as? Int let percentage2 = JSONArray[1]["percentage"] as? Double expect(taskId2).to(equal(task2.taskId)) expect(percentage2).to(equal(task2.percentage)) let taskId3 = JSONArray[2]["taskId"] as? Int let percentage3 = JSONArray[2]["percentage"] as? Double expect(taskId3).to(equal(task3.taskId)) expect(percentage3).to(equal(task3.percentage)) } func testSubclass() { var object = Subclass() object.base = "base var" object.sub = "sub var" let json = Mapper().toJSON(object) let parsedObject = Mapper<Subclass>().map(json) expect(object.base).to(equal(parsedObject?.base)) expect(object.sub).to(equal(parsedObject?.sub)) } func testGenericSubclass() { var object = GenericSubclass<String>() object.base = "base var" object.sub = "sub var" let json = Mapper().toJSON(object) let parsedObject = Mapper<GenericSubclass<String>>().map(json) expect(object.base).to(equal(parsedObject?.base)) expect(object.sub).to(equal(parsedObject?.sub)) } func testSubclassWithGenericArrayInSuperclass() { let JSONString = "{\"genericItems\":[{\"value\":\"value0\"}, {\"value\":\"value1\"}]}" let parsedObject = Mapper<SubclassWithGenericArrayInSuperclass<AnyObject>>().map(JSONString) let genericItems = parsedObject?.genericItems expect(genericItems).notTo(beNil()) expect(genericItems?[0].value).to(equal("value0")) expect(genericItems?[1].value).to(equal("value1")) } } class Response<T: Mappable>: Mappable { var result: T? class func newInstance() -> Mappable { return Response() } func mapping(map: Map) { result <- map["result"] } } class Status: Mappable { var status: Int? class func newInstance() -> Mappable { return Status() } func mapping(map: Map) { status <- map["code"] } } class Plan: Mappable { var tasks: [Task]? var dictionaryOfTasks: [String: [Task]]? class func newInstance() -> Mappable { return Plan() } func mapping(map: Map) { tasks <- map["tasks"] dictionaryOfTasks <- map["dictionaryOfTasks"] } } class Task: Mappable { var taskId: Int? var percentage: Double? class func newInstance() -> Mappable { return Task() } func mapping(map: Map) { taskId <- map["taskId"] percentage <- map["percentage"] } } class TaskDictionary: Mappable { var test: String? var tasks: [String : Task]? class func newInstance() -> Mappable { return TaskDictionary() } func mapping(map: Map) { test <- map["test"] tasks <- map["tasks"] } } // Confirm that struct can conform to `Mappable` struct Student: Mappable { var name: String? var UUID: String? var major: Int? var minor: Int? static func newInstance() -> Mappable { return Student() } mutating func mapping(map: Map) { name <- map["name"] UUID <- map["UUID"] major <- map["major"] minor <- map["minor"] } } enum Sex: String { case Male = "Male" case Female = "Female" } class User: Mappable { var username: String = "" var identifier: String? var photoCount: Int = 0 var age: Int? var weight: Double? var float: Float? var drinker: Bool = false var smoker: Bool? var sex: Sex? var arr: [AnyObject] = [] var arrOptional: [AnyObject]? var dict: [String : AnyObject] = [:] var dictOptional: [String : AnyObject]? var dictString: [String : String]? var friendDictionary: [String : User]? var friend: User? var friends: [User]? = [] class func newInstance() -> Mappable { return User() } func mapping(map: Map) { username <- map["username"] identifier <- map["identifier"] photoCount <- map["photoCount"] age <- map["age"] weight <- map["weight"] float <- map["float"] drinker <- map["drinker"] smoker <- map["smoker"] sex <- map["sex"] arr <- map["arr"] arrOptional <- map["arrOpt"] dict <- map["dict"] dictOptional <- map["dictOpt"] friend <- map["friend"] friends <- map["friends"] friendDictionary <- map["friendDictionary"] dictString <- map["dictString"] } } class Base: Mappable { var base: String? class func newInstance() -> Mappable { return Base() } func mapping(map: Map) { base <- map["base"] } } class Subclass: Base { var sub: String? override class func newInstance() -> Mappable { return Subclass() } override func mapping(map: Map) { super.mapping(map) sub <- map["sub"] } } class GenericSubclass<T>: Base { var sub: String? override class func newInstance() -> Mappable { return GenericSubclass<T>() } override func mapping(map: Map) { super.mapping(map) sub <- map["sub"] } } class WithGenericArray<T: Mappable>: Mappable { var genericItems: [T]? class func newInstance() -> Mappable { return WithGenericArray<T>() } func mapping(map: Map) { genericItems <- map["genericItems"] } } class ConcreteItem: Mappable { var value: String? class func newInstance() -> Mappable { return ConcreteItem() } func mapping(map: Map) { value <- map["value"] } } class SubclassWithGenericArrayInSuperclass<Unused>: WithGenericArray<ConcreteItem> { override class func newInstance() -> Mappable { return SubclassWithGenericArrayInSuperclass<Unused>() } } enum ExampleEnum: Int { case A case B case C } class ExampleEnumArray: Mappable { var enums: [ExampleEnum] = [] class func newInstance() -> Mappable { return ExampleEnumArray() } func mapping(map: Map) { enums <- map["enums"] } } class ExampleEnumDictionary: Mappable { var enums: [String: ExampleEnum] = [:] class func newInstance() -> Mappable { return ExampleEnumDictionary() } func mapping(map: Map) { enums <- map["enums"] } }
mit
a326fc54bdab4c414a540138bd10255c
26.912844
547
0.63358
3.595627
false
true
false
false
BeezleLabs/HackerTracker-iOS
hackertracker/LocationView.swift
1
5787
// // LocationView.swift // hackertracker // // Created by Seth W Law on 7/26/22. // Copyright © 2022 Beezle Labs. All rights reserved. // import Foundation import SwiftUI import UIKit struct LocationView: View { var locations: [HTLocationModel] let childLocations: [Int: [HTLocationModel]] var body: some View { VStack { List { ForEach(locations.filter { $0.hierDepth == 1 }.sorted { $0.hierExtentLeft < $1.hierExtentLeft }) { loc in LocationCell(location: loc, childLocations: childLocations) }.listRowBackground(Color.clear) } }.frame(maxWidth: .infinity, maxHeight: .infinity) .accentColor(Color.white) .onAppear { UITableView.appearance().backgroundColor = UIColor.clear UITableViewCell.appearance().backgroundColor = UIColor.clear } } init(locations: [HTLocationModel]) { self.locations = locations childLocations = childrenLocations(locations: locations) } } struct LocationCell: View { var location: HTLocationModel var childLocations: [Int: [HTLocationModel]] var dfu = DateFormatterUtility.shared @State private var showChildren = false var body: some View { VStack(alignment: .leading) { Button(action: { showChildren.toggle() }, label: { HStack(alignment: .center) { if location.hierDepth != 1 { Circle().foregroundColor(circleStatus(location: location)) .frame(width: heirCircle(heirDepth: location.hierDepth), height: heirCircle(heirDepth: location.hierDepth), alignment: .leading) } Text(location.shortName).font(heirFont(heirDepth: location.hierDepth)).fixedSize(horizontal: false, vertical: true).multilineTextAlignment(.leading) Spacer() if !(childLocations[location.id]?.isEmpty ?? false) { showChildren ? Image(systemName: "chevron.down") : Image(systemName: "chevron.left") } }.padding(.leading, CGFloat(location.hierDepth - 1) * 20.0) }).disabled(childLocations[location.id]?.isEmpty ?? true).buttonStyle(BorderlessButtonStyle()).foregroundColor(.white) if showChildren { ForEach(childLocations[location.id] ?? []) { loc in LocationCell(location: loc, childLocations: childLocations) } } } } } func childrenLocations(locations: [HTLocationModel]) -> [Int: [HTLocationModel]] { return locations.sorted { $0.hierExtentLeft < $1.hierExtentLeft }.reduce(into: [Int: [HTLocationModel]]()) { dict, loc in dict[loc.id] = locations.filter { $0.parentId == loc.id } } } func circleStatus(location: HTLocationModel) -> Color { let schedule = location.schedule let curDate = Date() if !schedule.isEmpty { if schedule.contains(where: { $0.status == "open" && curDate >= $0.begin && curDate <= $0.end }) { return .green } else if schedule.contains(where: { $0.status == "closed" && curDate >= $0.begin && curDate <= $0.end }) { return .red } else if schedule.allSatisfy({ $0.status == "closed" }) { return .red } } switch location.defaultStatus { case "open": return .green case "closed": return .red default: return .gray } } func heirCircle(heirDepth: Int) -> CGFloat { switch heirDepth { case 1: return 18 case 2: return 15 case 3: return 12 case 4: return 10 case 5: return 8 default: return 5 } } func heirFont(heirDepth: Int) -> Font { switch heirDepth { case 1: return Font.title.bold() case 2: return Font.headline case 3: return Font.callout case 4: return Font.subheadline case 5: return Font.body case 6: return Font.footnote default: return Font.caption } } class LocationUIView: UIViewController { var locationsToken: UpdateToken? var locations: [HTLocationModel] = [] override func viewDidLoad() { super.viewDidLoad() loadLocations() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let lvc = UIHostingController(rootView: LocationView(locations: locations)) addChild(lvc) view.addSubview(lvc.view) lvc.view.translatesAutoresizingMaskIntoConstraints = false lvc.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true lvc.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true lvc.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true lvc.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true navigationItem.title = "Locations" lvc.view.backgroundColor = UIColor(red: 45.0 / 255.0, green: 45.0 / 255.0, blue: 45.0 / 255.0, alpha: 1.0) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func loadLocations() { locationsToken = FSConferenceDataController.shared.requestLocations(forConference: AnonymousSession.shared.currentConference) { result in switch result { case let .success(locationList): self.locations = locationList self.viewDidAppear(true) case let .failure(error): NSLog("Load Locations Failure: \(error.localizedDescription)") } } } }
gpl-2.0
90328c1d1a7fc1d9807ec8c8ef7071a5
31.689266
168
0.600588
4.614035
false
false
false
false
loudnate/LoopKit
LoopKit/InsulinKit/ExponentialInsulinModel.swift
1
3462
// // ExponentialInsulinModel.swift // InsulinKit // // Created by Pete Schwamb on 7/30/17. // Copyright © 2017 LoopKit Authors. All rights reserved. // import Foundation public struct ExponentialInsulinModel { public let actionDuration: TimeInterval public let peakActivityTime: TimeInterval // Precomputed terms fileprivate let τ: Double fileprivate let a: Double fileprivate let S: Double /// Configures a new exponential insulin model /// /// - Parameters: /// - actionDuration: The total duration on insulin activity /// - peakActivityTime: The time of the peak of insulin activity from dose. public init(actionDuration: TimeInterval, peakActivityTime: TimeInterval) { self.actionDuration = actionDuration self.peakActivityTime = peakActivityTime self.τ = peakActivityTime * (1 - peakActivityTime / actionDuration) / (1 - 2 * peakActivityTime / actionDuration) self.a = 2 * τ / actionDuration self.S = 1 / (1 - a + (1 + a) * exp(-actionDuration / τ)) } } extension ExponentialInsulinModel: InsulinModel { public var effectDuration: TimeInterval { return self.actionDuration } /// Returns the percentage of total insulin effect remaining at a specified interval after delivery; /// also known as Insulin On Board (IOB). /// /// This is a configurable exponential model as described here: https://github.com/LoopKit/Loop/issues/388#issuecomment-317938473 /// Allows us to specify time of peak activity, as well as duration, and provides activity and IOB decay functions /// Many thanks to Dragan Maksimovic (@dm61) for creating such a flexible way of adjusting an insulin curve /// for use in closed loop systems. /// /// - Parameter time: The interval after insulin delivery /// - Returns: The percentage of total insulin effect remaining public func percentEffectRemaining(at time: TimeInterval) -> Double { switch time { case let t where t <= 0: return 1 case let t where t >= actionDuration: return 0 default: return 1 - S * (1 - a) * ((pow(time, 2) / (τ * actionDuration * (1 - a)) - time / τ - 1) * exp(-time / τ) + 1) } } } extension ExponentialInsulinModel: CustomDebugStringConvertible { public var debugDescription: String { return "ExponentialInsulinModel(actionDuration: \(actionDuration), peakActivityTime: \(peakActivityTime))" } } #if swift(>=4) extension ExponentialInsulinModel: Decodable { enum CodingKeys: String, CodingKey { case actionDuration = "actionDuration" case peakActivityTime = "peakActivityTime" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let actionDuration: Double = try container.decode(Double.self, forKey: .actionDuration) let peakActivityTime: Double = try container.decode(Double.self, forKey: .peakActivityTime) self.init(actionDuration: actionDuration, peakActivityTime: peakActivityTime) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(actionDuration, forKey: .actionDuration) try container.encode(peakActivityTime, forKey: .peakActivityTime) } } #endif
mit
36e1d551341e061649a56633351a7b61
36.956044
133
0.678344
4.913229
false
false
false
false
xmartlabs/Swift-Project-Template
Project-iOS/XLProjectName/XLProjectName/Helpers/Extensions/AppDelegate+XLProjectName.swift
1
2071
// // AppDelegate+XLProjectName.swift // XLProjectName // // Created by XLAuthorName ( XLAuthorWebsite ) // Copyright © 2016 'XLOrganizationName'. All rights reserved. // import Foundation import Fabric import Alamofire import Eureka import Crashlytics extension AppDelegate { func setupCrashlytics() { Fabric.with([Crashlytics.self]) Fabric.sharedSDK().debug = Constants.Debug.crashlytics } // MARK: Alamofire notifications func setupNetworking() { NotificationCenter.default.addObserver( self, selector: #selector(AppDelegate.requestDidComplete(_:)), name: Alamofire.Request.didCompleteTaskNotification, object: nil) } @objc func requestDidComplete(_ notification: Notification) { guard let request = notification.request, let response = request.response else { DEBUGLog("Request object not a task") return } if Constants.Network.successRange ~= response.statusCode { if let token = response.allHeaderFields["Set-Cookie"] as? String { SessionController.sharedInstance.token = token } } else if response.statusCode == Constants.Network.Unauthorized && SessionController.sharedInstance.isLoggedIn() { SessionController.sharedInstance.clearSession() // here you should implement AutoLogout: Transition to login screen and show an appropiate message } } /** Set up your Eureka default row customization here */ func stylizeEurekaRows() { let genericHorizontalMargin = CGFloat(50) BaseRow.estimatedRowHeight = 58 EmailRow.defaultRowInitializer = { $0.placeholder = NSLocalizedString("E-mail Address", comment: "") $0.placeholderColor = .gray } EmailRow.defaultCellSetup = { cell, _ in cell.layoutMargins = .zero cell.contentView.layoutMargins.left = genericHorizontalMargin cell.height = { 58 } } } }
mit
ffa4aac88ebd8b42b5cb08495807e54c
30.846154
122
0.647343
5.136476
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Deal/Controllers/YD_DatePickerViewController.swift
4
2732
// // YD_DatePickerViewController.swift // 渐变色 // // Created by J-bb on 17/5/24. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit protocol SureActionDelegate { func sureAction(date:Date) } class YD_DatePickerViewController: UIViewController { var picker:UIDatePicker = { let picker = UIDatePicker(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 200, width: UIScreen.main.bounds.size.width, height: 200)) picker.datePickerMode = .date picker.backgroundColor = UIColor.white return picker }() var delegate:SureActionDelegate? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clear view.addSubview(picker) picker.maximumDate = Date() let menuView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 200 - 40, width: UIScreen.main.bounds.size.width, height: 40)) view.addSubview(menuView) menuView.backgroundColor = UIColor.white let cancelButton = UIButton(frame: CGRect(x: 25, y: 0, width: 40, height: 40)) cancelButton.setTitle("取消", for: .normal) cancelButton.setTitleColor(UIColor.green, for: .normal) menuView.addSubview(cancelButton) cancelButton.addTarget(self, action: #selector(cancelButtonAction), for: .touchUpInside) let sureButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.size.width - 25 - 40, y: 0, width: 40, height: 40)) sureButton.addTarget(self, action: #selector(sureButtonAction), for: .touchUpInside) sureButton.setTitleColor(UIColor.green, for: .normal) sureButton.setTitle("确定", for: .normal) menuView.addSubview(sureButton) } func cancelButtonAction() { dismiss(animated: true, completion: nil) } func sureButtonAction() { delegate?.sureAction(date: picker.date) dismiss(animated: true, completion: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ }
gpl-3.0
18cb83746e30c544d3c940f258a89b4e
33.807692
150
0.660405
4.386107
false
false
false
false
ahoppen/swift
test/Distributed/Runtime/distributed_actor_func_calls_remoteCall_takeThrowReturn.swift
4
1942
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift // RUN: %target-build-swift -module-name main -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s --color // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574 // UNSUPPORTED: windows import Distributed import FakeDistributedActorSystems typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem distributed actor Greeter { distributed func takeThrowReturn(name: String) async throws -> String { throw SomeError() } } struct SomeError: Error, Sendable, Codable {} func test() async throws { let system = DefaultDistributedActorSystem() let local = Greeter(actorSystem: system) let ref = try Greeter.resolve(id: local.id, using: system) do { let value = try await ref.takeThrowReturn(name: "Example") // CHECK: >> remoteCall: on:main.Greeter, target:main.Greeter.takeThrowReturn(name:), invocation:FakeInvocationEncoder(genericSubs: [], arguments: ["Example"], returnType: Optional(Swift.String), errorType: Optional(Swift.Error)), throwing:Swift.Error, returning:Swift.String print("did not throw") // CHECK-NOT: did not throw } catch { // CHECK: << onThrow: SomeError() // CHECK: << remoteCall throw: SomeError() print("error: \(error)") // CHECK: error: SomeError() } } @main struct Main { static func main() async { try! await test() } }
apache-2.0
6c2780150f0a9b4219fcf0ec819068fa
34.962963
279
0.73275
4.029046
false
true
false
false
DroidsOnRoids/Habit
Example/Habit/ViewController.swift
1
1215
// // ViewController.swift // Habit // // Created by Piotr Sochalewski on 04/20/2016. // Copyright (c) 2016 Droids On Roids. All rights reserved. // import UIKit import UserNotifications import Habit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if #available(iOS 10.0, tvOS 10.0, watchOS 3.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in print("Access granted: \(granted.description)") } let notification = UNMutableNotificationContent() notification.body = "Example notification" _ = notification.repeatEvery(.minute) } else { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)) let notification = UILocalNotification() notification.alertBody = "Example notification" _ = notification.repeatEvery(.day(time: Date())) UIApplication.shared.scheduleLocalNotification(notification) } } }
mit
d7b7472820ef378898af6a25990b2473
32.75
143
0.627984
5.170213
false
false
false
false
blstream/mEatUp
mEatUp/mEatUp/RoomDetailsViewController.swift
1
11648
// // RoomDetailsViewController.swift // mEatUp // // Created by Krzysztof Przybysz on 13/04/16. // Copyright © 2016 BLStream. All rights reserved. // import UIKit import CloudKit class RoomDetailsViewController: UIViewController { @IBOutlet weak var contentView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var placeTextField: UITextField! @IBOutlet weak var dateTextField: UITextField! @IBOutlet weak var hourTextField: UITextField! @IBOutlet weak var limitSlider: UISlider! @IBOutlet weak var limitLabel: UILabel! @IBOutlet weak var privateSwitch: UISwitch! @IBOutlet weak var rightBarButton: UIBarButtonItem! @IBOutlet weak var limitText: UILabel! @IBOutlet weak var privateText: UILabel! @IBOutlet weak var topTextField: UITextField! @IBOutlet weak var topLabel: UILabel! var activeField: UITextField? var room: Room? var chosenRestaurant: Restaurant? let datePicker = MeatupDatePicker() let formatter = NSDateFormatter() let stringLengthLimit = 30 let cloudKitHelper = CloudKitHelper() var viewPurpose: RoomDetailsPurpose? var userRecordID: CKRecordID? @IBAction func sliderValueChanged(sender: UISlider) { limitLabel.text = "\(Int(sender.value))" } @IBAction func placeTextFieldEditing(sender: UITextField) { performSegueWithIdentifier("ShowRestaurantListViewController", sender: nil) } @IBAction func dateTextFieldEditing(sender: UITextField) { datePicker.date = NSDate() datePicker.datePickerMode = .Date sender.inputAccessoryView = datePicker.toolBar() datePicker.doneButtonAction = { [weak self] date in self?.dateTextField.text = self?.formatter.stringFromDate(date, withFormat: "dd.MM.yyyy") self?.view.endEditing(true) } datePicker.cancelButtonAction = { [weak self] in self?.view.endEditing(true) } sender.inputView = datePicker } @IBAction func hourTextFieldEditing(sender: UITextField) { datePicker.datePickerMode = .Time sender.inputAccessoryView = datePicker.toolBar() datePicker.doneButtonAction = { [weak self] date in self?.hourTextField.text = self?.formatter.stringFromDate(date, withFormat: "H:mm") self?.view.endEditing(true) } datePicker.cancelButtonAction = { [weak self] in self?.view.endEditing(true) } sender.inputView = datePicker } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let navigationCtrl = segue.destinationViewController as? UINavigationController, let destination = navigationCtrl.topViewController as? RestaurantListViewController { destination.saveRestaurant = { [weak self] restaurant in self?.placeTextField.text = restaurant.name self?.chosenRestaurant = restaurant } } } func registerForKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWasShown), name: UIKeyboardDidShowNotification, object: nil) } func keyboardWasShown(aNotification: NSNotification) { let info = aNotification.userInfo if let keyboardSize = (info?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { let contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets var aRect = self.view.frame aRect.size.height -= keyboardSize.height if let activeFieldFrame = activeField?.frame { if CGRectContainsPoint(aRect, activeFieldFrame.origin) { scrollView.scrollRectToVisible(activeFieldFrame, animated: true) } } } } func keyboardWillBeHidden(aNotification: NSNotification) { let contentInsets = UIEdgeInsetsZero scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets } override func viewDidLoad() { super.viewDidLoad() determineViewPurpose() guard let viewPurpose = viewPurpose else { return } setupViewForPurpose(viewPurpose) limitLabel.text = "\(room?.maxCount ?? Int(limitSlider.minimumValue))" datePicker.locale = NSLocale(localeIdentifier: "PL") registerForKeyboardNotifications() self.navigationController?.navigationBar.translucent = false; } func determineViewPurpose() { if room == nil { viewPurpose = RoomDetailsPurpose.Create } else if room?.owner?.recordID == userRecordID && room?.didEnd == false { viewPurpose = RoomDetailsPurpose.Edit } else { viewPurpose = RoomDetailsPurpose.View } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func setupViewForPurpose(purpose: RoomDetailsPurpose) { switch purpose { case .Create: rightBarButton.title = RoomDetailsPurpose.Create.rawValue enableUserInteraction(true) case .Edit: if let room = room { configureWithRoom(room) } rightBarButton.title = RoomDetailsPurpose.Edit.rawValue enableUserInteraction(true) case .View: topLabel.text = "Owner" topTextField.placeholder = "Owner" if let room = room { configureWithRoom(room) } navigationItem.rightBarButtonItems?.removeAll() enableUserInteraction(false) } } func enableUserInteraction(bool: Bool) { topTextField.userInteractionEnabled = bool placeTextField.userInteractionEnabled = bool dateTextField.userInteractionEnabled = bool hourTextField.userInteractionEnabled = bool limitSlider.userInteractionEnabled = bool privateSwitch.userInteractionEnabled = bool } func configureWithRoom(room: Room) { title = "\(room.title ?? "Room")" guard let viewPurpose = viewPurpose else { return } if let name = room.owner?.name, let surname = room.owner?.surname, let date = room.date, let limit = room.maxCount, let access = room.accessType { switch viewPurpose { case .View: topTextField.text = "\(name) \(surname)" case .Edit: topTextField.text = room.title case .Create: break } if room.didEnd == true { privateSwitch.hidden = true limitSlider.hidden = true limitText.hidden = true privateText.hidden = true limitLabel.hidden = true } placeTextField.text = room.restaurant?.name hourTextField.text = formatter.stringFromDate(date, withFormat: "H:mm") dateTextField.text = formatter.stringFromDate(date, withFormat: "dd.MM.yyyy") limitSlider.value = Float(limit) privateSwitch.on = access == AccessType.Private ? true : false } } func textFieldsAreFilled() -> Bool { guard let topText = topTextField.text, placeText = placeTextField.text, dateText = dateTextField.text, hourText = hourTextField.text else { return false } if !topText.isEmpty && !placeText.isEmpty && !dateText.isEmpty && !hourText.isEmpty { return true } return false } func createRoom() { rightBarButton.enabled = false room = Room() room?.owner?.recordID = userRecordID room?.maxCount = Int(limitSlider.value) room?.accessType = AccessType(rawValue: privateSwitch.on ? AccessType.Private.rawValue : AccessType.Public.rawValue) room?.title = topTextField.text if let day = dateTextField.text, hour = hourTextField.text { room?.date = formatter.dateFromString(day, hour: hour) } if let restaurant = chosenRestaurant { room?.restaurant = restaurant } if let room = room where textFieldsAreFilled() { cloudKitHelper.saveRoomRecord(room, completionHandler: { if let userRecordID = self.userRecordID, let roomRecordID = room.recordID { let userInRoom = UserInRoom(userRecordID: userRecordID, roomRecordID: roomRecordID, confirmationStatus: ConfirmationStatus.Accepted) self.cloudKitHelper.saveUserInRoomRecord(userInRoom, completionHandler: { self.navigationController?.popViewControllerAnimated(true) }, errorHandler: nil) } }, errorHandler: nil) } else { rightBarButton.enabled = true AlertCreator.singleActionAlert("Error", message: "Please fill all text fields.", actionTitle: "OK", actionHandler: nil) } } func updateRoom(room: Room) { room.title = topTextField.text room.restaurant?.name = placeTextField.text if let day = dateTextField.text, hour = hourTextField.text { room.date = formatter.dateFromString(day, hour: hour) } room.maxCount = Int(limitSlider.value) room.accessType = AccessType(rawValue: privateSwitch.on ? AccessType.Private.rawValue : AccessType.Public.rawValue) if let restaurant = chosenRestaurant { room.restaurant = restaurant } if textFieldsAreFilled() { cloudKitHelper.editRoomRecord(room, completionHandler: { self.navigationController?.popViewControllerAnimated(true) }, errorHandler: nil) } else { rightBarButton.enabled = true AlertCreator.singleActionAlert("Error", message: "Please fill all text fields.", actionTitle: "OK", actionHandler: nil) } } @IBAction func barButtonPressed(sender: UIBarButtonItem) { sender.enabled = false guard let viewPurpose = viewPurpose else { return } switch viewPurpose { case .Create: createRoom() case .Edit: if let room = room { updateRoom(room) } case .View: break } } } extension RoomDetailsViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if textField == hourTextField || textField == dateTextField || textField == placeTextField { return false } return true } func textFieldDidBeginEditing(textField: UITextField) { activeField = textField } func textFieldDidEndEditing(textField: UITextField) { activeField = nil } }
apache-2.0
33449a507eb543fd1903f85a4cdddec0
36.330128
177
0.62514
5.62929
false
false
false
false
rnystrom/GitHawk
Local Pods/GitHubAPI/GitHubAPI/V3NotificationSubject.swift
1
1574
// // V3NotificationSubject.swift // GitHubAPI // // Created by Ryan Nystrom on 3/3/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import Foundation public struct V3NotificationSubject: Codable { public enum SubjectType: String, Codable { case issue = "Issue" case pullRequest = "PullRequest" case commit = "Commit" case repo = "Repository" case release = "Release" case invitation = "RepositoryInvitation" case vulnerabilityAlert = "RepositoryVulnerabilityAlert" } public let title: String public let type: SubjectType public let url: URL? } public extension V3NotificationSubject { enum Identifier { case number(Int) case hash(String) case release(String) public var string: String { switch self { case .number(let n): return "#\(n)" case .hash(let h): return h case .release(let r): return r } } } var identifier: Identifier? { guard let url = self.url else { return nil } let split = url.absoluteString.components(separatedBy: "/") guard split.count > 2, let identifier = split.last else { return nil } let type = split[split.count - 2] switch type { case "commits": return .hash(identifier) case "releases": return .release(identifier) default: return .number((identifier as NSString).integerValue) } } }
mit
c71e89a28479a940a968251c16038ab2
23.578125
67
0.581691
4.55942
false
false
false
false
eswick/StreamKit
Sources/FileStream.swift
1
8221
#if os(Linux) import Glibc #else import Darwin #endif public enum FileAccess { case ReadOnly case ReadWrite case WriteOnly } public enum FileMode { case Append case Create case CreateNew case Open case OpenOrCreate case Truncate } public struct FilePermissions: OptionSetType { public static let Read = FilePermissions(read: true) public static let Write = FilePermissions(write: true) public static let Execute = FilePermissions(execute: true) public var read: Bool = false public var write: Bool = false public var execute: Bool = false public var rawValue: UInt8 { get { var val: UInt8 = 0 if read { val |= 1 } if write { val |= 2 } if execute { val |= 4 } return val } set { if newValue & 1 == 1 { read = true } if newValue & 2 == 2 { write = true } if newValue & 4 == 4 { execute = true } } } public init(read: Bool = false, write: Bool = false, execute: Bool = false) { self.read = read self.write = write self.execute = execute } public init(rawValue: UInt8) { self.rawValue = rawValue } } public func == (left: FilePermissions, right: FilePermissions) -> Bool { return left.rawValue == right.rawValue } public struct FileFlags { private(set) var userPermissions: FilePermissions = FilePermissions() private(set) var groupPermissions: FilePermissions = FilePermissions() private(set) var otherPermissions: FilePermissions = FilePermissions() private(set) var setuid: Bool = false private(set) var setgid: Bool = false private(set) var sticky: Bool = false #if os(Linux) public typealias fileflags_t = UInt32 #else public typealias fileflags_t = UInt16 #endif private(set) var rawValue: fileflags_t { get { var val: fileflags_t = 0 if userPermissions.read { val |= S_IRUSR } if userPermissions.write { val |= S_IWUSR } if userPermissions.execute { val |= S_IXUSR } if groupPermissions.read { val |= S_IRGRP } if groupPermissions.write { val |= S_IWGRP } if groupPermissions.execute { val |= S_IXGRP } if otherPermissions.read { val |= S_IROTH } if otherPermissions.write { val |= S_IWOTH } if otherPermissions.execute { val |= S_IXOTH } if setuid { val |= S_ISUID } if setgid { val |= S_ISGID } if sticky { val |= S_ISVTX } return val } set { userPermissions.read = (newValue & S_IRUSR == S_IRUSR) userPermissions.write = (newValue & S_IWUSR == S_IWUSR) userPermissions.execute = (newValue & S_IXUSR == S_IXUSR) groupPermissions.read = (newValue & S_IRGRP == S_IRGRP) groupPermissions.write = (newValue & S_IWGRP == S_IWGRP) groupPermissions.execute = (newValue & S_IXGRP == S_IXGRP) otherPermissions.read = (newValue & S_IROTH == S_IROTH) otherPermissions.write = (newValue & S_IWOTH == S_IWOTH) otherPermissions.execute = (newValue & S_IXOTH == S_IXOTH) setuid = (newValue & S_ISUID == S_ISUID) setgid = (newValue & S_ISGID == S_ISGID) sticky = (newValue & S_ISVTX == S_ISVTX) } } public var octalRepresentation: String { get { return String(self.rawValue, radix: 8) } } public init(rawValue: fileflags_t) { self.rawValue = rawValue } public init?(octalRepresentation rep: String) { if rep.characters.count == 3 { var str = "0" str.appendContentsOf(rep) if let val = fileflags_t(str, radix: 8) { self.rawValue = val } else { return nil } } else if rep.characters.count == 4 { if let val = fileflags_t(rep, radix: 8) { self.rawValue = val } else { return nil } } else { return nil } } public init?(octalRepresentation rep: UInt) { let strRep = String(rep) self.init(octalRepresentation: strRep) } public init() { self.rawValue = 0 } } public func == (left: FileFlags, right: FileFlags) -> Bool { return left.rawValue == right.rawValue } public enum FileStreamError: ErrorType { case OpenFailed(Int32) case InvalidArgument(String) case FileNotFound case FileExists } private func fileExists(path: String) -> Bool { #if os(Linux) return Glibc.access(path, F_OK) != -1 #else return Darwin.access(path, F_OK) != -1 #endif } private func fileIsReadable(path: String) -> Bool { #if os(Linux) return Glibc.access(path, R_OK) != -1 #else return Darwin.access(path, R_OK) != -1 #endif } private func fileIsWritable(path: String) -> Bool { #if os(Linux) return Glibc.access(path, W_OK) != -1 #else return Darwin.access(path, W_OK) != -1 #endif } public class FileStream: IOStream { let path: String let mode: FileMode let access: FileAccess public init(path: String, mode: FileMode = .OpenOrCreate, access: FileAccess = .ReadWrite, creationFlags: FileFlags = FileFlags(rawValue: 0o644)) throws { self.path = path self.mode = mode self.access = access var readable = false var writable = false var flags: Int32 switch access { case .ReadOnly: flags = O_RDONLY readable = true break case .WriteOnly: flags = O_WRONLY writable = true break case .ReadWrite: flags = O_RDWR readable = true writable = true break } switch mode { case .Append: if readable { throw FileStreamError.InvalidArgument("Read access not allowed with FileMode.Append") } if !fileExists(path) { throw FileStreamError.FileNotFound } flags |= O_APPEND break case .Create: if !writable { throw FileStreamError.InvalidArgument("Write access required with FileMode.Create") } if !fileExists(path) { flags |= O_CREAT } else { flags |= O_TRUNC } break case .CreateNew: if fileExists(path) { throw FileStreamError.FileExists } flags |= O_CREAT break case .Open: if !fileExists(path) { throw FileStreamError.FileNotFound } break case .OpenOrCreate: if !fileExists(path) { flags |= O_CREAT } break case .Truncate: if !fileExists(path) { throw FileStreamError.FileNotFound } flags |= O_TRUNC break } let openResult = open(path, flags, creationFlags.rawValue) if openResult == -1 { throw FileStreamError.OpenFailed(errno) } super.init(fileDescriptor: openResult, canRead: readable, canWrite: writable, canTimeout: false, canSeek: true) } }
mit
7b005ea9a3bdb02281c0365dc8d119a5
25.869281
158
0.504926
4.73015
false
false
false
false
mirrorinf/Mathematicus
Mathematicus/Derivative.swift
1
1412
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation extension Polynomial where Field: Continuum { func evaluateDerivative(at x: Field) -> Field { var rst = Field.zero var run = Field.identity for i in 1...self.maxexp { if let c = self.coffcient[i] { let term = c * Field.realNumber(Double(i)) * run rst = rst + term } run = run * x } return rst } var derivative: Polynomial<Field> { var coff: [Int : Field] = [ : ] for i in 1..<self.maxexp { if let c = self.coffcient[i] { coff[i - 1] = c * Field.realNumber(Double(i)) } } return Polynomial<Field>(coffcient: coff, maxexp: self.maxexp - 1) } }
apache-2.0
27b73a892bd6f8a7adf11804f3014fdf
31.860465
68
0.6983
3.503722
false
false
false
false
springware/cloudsight-swift
Example-swift/Pods/CloudSight/CloudSight/CloudSightConnection.swift
2
1481
// // CloudSightConnection.swift // CloudSight // // Created by OCR Labs on 3/7/17. // Copyright © 2017 OCR Labs. All rights reserved. // import UIKit public class CloudSightConnection: NSObject { public var consumerKey: String = "" public var consumerSecret: String = "" static var _instance = CloudSightConnection() public class func sharedInstance() -> CloudSightConnection { return _instance } func authorizationHeaderWithUrl(url: String) ->NSString { return authorizationHeaderWithUrl(url, withParameters: [:]) } func authorizationHeaderWithUrl(url: String, withParameters parameters: NSDictionary ) ->NSString { return authorizationHeaderWithUrl(url, withParameters: parameters, withMethod: kBFOAuthGETRequestMethod) } func authorizationHeaderWithUrl(url: String, withParameters parameters: NSDictionary , withMethod method: String) ->NSString { assert(!consumerKey.isEmpty , "consumerKey property is set to nil, be sure to set credentials") assert(!consumerSecret.isEmpty, "consumerSecret property is set to nil, be sure to set credentials") let oauth = BFOAuth(consumerKey: self.consumerKey, consumerSecret:self.consumerSecret, accessToken:"", tokenSecret:"") oauth.requestURL = NSURL(string: url)! oauth.requestMethod = method oauth.requestParameters = parameters return oauth.authorizationHeader() } }
mit
128b16d3c9d3f14f549886722b65e688
36.948718
130
0.704054
5.266904
false
false
false
false
prolificinteractive/Yoshi
Example/YoshiExample/ViewController.swift
1
1501
// // ViewController.swift // YoshiExample // // Created by Michael Campbell on 12/22/15. // Copyright © 2015 Prolific Interactive. All rights reserved. // import UIKit final class ViewController: UIViewController { @IBOutlet private weak var environment: UILabel! { didSet { environment.text = environmentName } } @IBOutlet private weak var environmentDate: UILabel! private let dateFormatter: DateFormatter = DateFormatter() private var environmentName: String? { didSet { environment?.text = environmentName } } override func viewDidLoad() { super.viewDidLoad() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short NotificationCenter.default .addObserver(self, selector: #selector(ViewController.didUpdateEnvironmentDate(_:)), name: NSNotification.Name(rawValue: Notifications.EnvironmentDateUpdatedNotification), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func updateEnvironment(name: String, url: URL) { environmentName = name } @objc func didUpdateEnvironmentDate(_ notification: Notification) { guard let environmentDate = notification.object as? Date else { return } self.environmentDate.text = dateFormatter.string(from: environmentDate) } }
mit
d2cfb7186f83deeab3e43ed5486d5fa0
25.315789
111
0.634667
5.319149
false
false
false
false
auth0/Lock.iOS-OSX
Lock/UnrecoverableErrorView.swift
1
5602
// UnrecoverableErrorView.swift // // Copyright (c) 2017 Auth0 (http://auth0.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 UIKit class UnrecoverableErrorView: UIView, View { weak var secondaryButton: SecondaryButton? weak var messageLabel: UILabel? private weak var titleLabel: UILabel? init(canRetry: Bool) { let center = UILayoutGuide() let titleLabel = UILabel() let messageLabel = UILabel() let imageView = UIImageView() let actionButton = SecondaryButton() self.secondaryButton = actionButton self.messageLabel = messageLabel self.titleLabel = titleLabel super.init(frame: CGRect.zero) self.addSubview(imageView) self.addSubview(titleLabel) self.addSubview(messageLabel) self.addSubview(actionButton) self.addLayoutGuide(center) constraintEqual(anchor: center.leftAnchor, toAnchor: self.leftAnchor) constraintEqual(anchor: center.topAnchor, toAnchor: self.topAnchor) constraintEqual(anchor: center.rightAnchor, toAnchor: self.rightAnchor) constraintEqual(anchor: center.bottomAnchor, toAnchor: self.bottomAnchor) constraintEqual(anchor: imageView.centerXAnchor, toAnchor: center.centerXAnchor) constraintEqual(anchor: imageView.centerYAnchor, toAnchor: center.centerYAnchor, constant: -90) imageView.translatesAutoresizingMaskIntoConstraints = false constraintEqual(anchor: titleLabel.leftAnchor, toAnchor: self.leftAnchor, constant: 20) constraintEqual(anchor: titleLabel.rightAnchor, toAnchor: self.rightAnchor, constant: -20) constraintEqual(anchor: titleLabel.centerYAnchor, toAnchor: center.centerYAnchor, constant: -15) titleLabel.translatesAutoresizingMaskIntoConstraints = false constraintEqual(anchor: messageLabel.leftAnchor, toAnchor: self.leftAnchor, constant: 20) constraintEqual(anchor: messageLabel.rightAnchor, toAnchor: self.rightAnchor, constant: -20) constraintEqual(anchor: messageLabel.topAnchor, toAnchor: titleLabel.bottomAnchor, constant: 15) messageLabel.translatesAutoresizingMaskIntoConstraints = false constraintEqual(anchor: actionButton.centerXAnchor, toAnchor: center.centerXAnchor) constraintEqual(anchor: actionButton.topAnchor, toAnchor: messageLabel.bottomAnchor, constant: 10) actionButton.translatesAutoresizingMaskIntoConstraints = false imageView.image = LazyImage(name: "ic_connection_error", bundle: bundleForLock()).image(compatibleWithTraits: self.traitCollection) titleLabel.textAlignment = .center titleLabel.font = lightSystemFont(size: 22) titleLabel.numberOfLines = 1 titleLabel.textColor = Style.Auth0.textColor messageLabel.textAlignment = .center messageLabel.font = regularSystemFont(size: 15) messageLabel.textColor = Style.Auth0.textColor.withAlphaComponent(0.50) messageLabel.numberOfLines = 3 actionButton.button?.setTitleColor(UIColor(red: 0.04, green: 0.53, blue: 0.69, alpha: 1.0), for: .normal) actionButton.button?.titleLabel?.font = regularSystemFont(size: 16) if canRetry { titleLabel.text = "Can't load the login box".i18n(key: "com.auth0.lock.error.recoverable.title", comment: "Recoverable error title") messageLabel.text = "Please check your internet connection.".i18n(key: "com.auth0.lock.error.recoverable.message", comment: "Recoverable error message") actionButton.title = "Retry".i18n(key: "com.auth0.lock.error.recoverable.button", comment: "Recoverable error button") } else { titleLabel.text = "Can't resolve your request".i18n(key: "com.auth0.lock.error.unrecoverable.title", comment: "Unrecoverable error title") messageLabel.text = "There was an unexpected error while resolving the login box configuration, please contact support.".i18n(key: "com.auth0.lock.error.unrecoverable.message.no_action", comment: "Unrecoverable error message") actionButton.title = "Contact support".i18n(key: "com.auth0.lock.error.unrecoverable.button", comment: "Unrecoverable error button") actionButton.isHidden = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func apply(style: Style) { self.titleLabel?.textColor = style.textColor self.messageLabel?.textColor = style.textColor.withAlphaComponent(0.50) } }
mit
03e8510f8aaa06baf03b839c8492914c
51.849057
238
0.728668
4.846021
false
false
false
false
codelynx/silvershadow
Silvershadow/PatternRenderer.swift
1
7444
// // ImageRenderer.swift // Silvershadow // // Created by Kaz Yoshikawa on 12/22/15. // Copyright © 2016 Electricwoods LLC. All rights reserved. // import Foundation import CoreGraphics import MetalKit import GLKit import simd // // ImageRenderer // class PatternRenderer: Renderer { typealias VertexType = Vertex // MARK: - struct Vertex { var x, y, z, w, u, v: Float var padding: SIMD2<Float> init(x: Float, y: Float, z: Float, w: Float, u: Float, v: Float) { self.x = x self.y = y self.z = z self.w = w self.u = u self.v = v self.padding = .init() } } struct Uniforms { var transform: GLKMatrix4 var contentSize: SIMD2<Float> var patternSize: SIMD2<Float> } let device: MTLDevice required init(device: MTLDevice) { self.device = device } func vertices(for rect: Rect) -> [Vertex] { let (l, r, t, b) = (rect.minX, rect.maxX, rect.maxY, rect.minY) // vertex (y) texture (v) // 1---4 (1) a---d (0) // | | | | // 2---3 (0) b---c (1) // return [ Vertex(x: l, y: t, z: 0, w: 1, u: 0, v: 0), // 1, a Vertex(x: l, y: b, z: 0, w: 1, u: 0, v: 1), // 2, b Vertex(x: r, y: b, z: 0, w: 1, u: 1, v: 1), // 3, c Vertex(x: l, y: t, z: 0, w: 1, u: 0, v: 0), // 1, a Vertex(x: r, y: b, z: 0, w: 1, u: 1, v: 1), // 3, c Vertex(x: r, y: t, z: 0, w: 1, u: 1, v: 0), // 4, d ] } var vertexDescriptor: MTLVertexDescriptor { let vertexDescriptor = MTLVertexDescriptor() vertexDescriptor.attributes[0].offset = 0 vertexDescriptor.attributes[0].format = .float4 vertexDescriptor.attributes[0].bufferIndex = 0 vertexDescriptor.attributes[1].offset = 0 vertexDescriptor.attributes[1].format = .float2 vertexDescriptor.attributes[1].bufferIndex = 0 vertexDescriptor.layouts[0].stepFunction = .perVertex vertexDescriptor.layouts[0].stride = MemoryLayout<Vertex>.size return vertexDescriptor } lazy var renderPipelineState: MTLRenderPipelineState = { let renderPipelineDescriptor = MTLRenderPipelineDescriptor() renderPipelineDescriptor.vertexDescriptor = self.vertexDescriptor renderPipelineDescriptor.vertexFunction = self.library.makeFunction(name: "pattern_vertex")! renderPipelineDescriptor.fragmentFunction = self.library.makeFunction(name: "pattern_fragment")! renderPipelineDescriptor.colorAttachments[0].pixelFormat = .`default` renderPipelineDescriptor.colorAttachments[0].isBlendingEnabled = true renderPipelineDescriptor.colorAttachments[0].rgbBlendOperation = .add renderPipelineDescriptor.colorAttachments[0].alphaBlendOperation = .add renderPipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = .one renderPipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = .one renderPipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha renderPipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha return try! self.device.makeRenderPipelineState(descriptor: renderPipelineDescriptor) }() lazy var shadingSamplerState: MTLSamplerState = { return self.device.makeSamplerState(descriptor: .`default`)! }() lazy var patternSamplerState: MTLSamplerState = { return self.device.makeSamplerState(descriptor: .`default`)! }() func vertexBuffer(for vertices: [Vertex]) -> VertexBuffer<Vertex>? { return VertexBuffer(device: device, vertices: vertices) } func vertexBuffer(for rect: Rect) -> VertexBuffer<Vertex>? { return VertexBuffer(device: device, vertices: vertices(for: rect)) } func texture(of image: XImage) -> MTLTexture? { guard let cgImage: CGImage = image.cgImage else { return nil } var options: [String : NSObject] = [convertFromMTKTextureLoaderOption(MTKTextureLoader.Option.SRGB): false as NSNumber] if #available(iOS 10.0, *) { options[convertFromMTKTextureLoaderOption(MTKTextureLoader.Option.origin)] = true as NSNumber } return try? device.textureLoader.newTexture(cgImage: cgImage, options: convertToOptionalMTKTextureLoaderOptionDictionary(options)) } // MARK: - // prepare triple reusable buffers for avoid race condition lazy var uniformTripleBuffer: [MTLBuffer] = { return [ self.device.makeBuffer(length: MemoryLayout<Uniforms>.size, options: [.storageModeShared])!, self.device.makeBuffer(length: MemoryLayout<Uniforms>.size, options: [.storageModeShared])!, self.device.makeBuffer(length: MemoryLayout<Uniforms>.size, options: [.storageModeShared])! ] }() let rectangularVertexCount = 6 lazy var rectVertexTripleBuffer: [MTLBuffer] = { let len = MemoryLayout<Vertex>.size * self.rectangularVertexCount return [ self.device.makeBuffer(length: len, options: [.storageModeShared])!, self.device.makeBuffer(length: len, options: [.storageModeShared])!, self.device.makeBuffer(length: len, options: [.storageModeShared])! ] }() var tripleBufferIndex = 0 func renderPattern(context: RenderContext, in rect: Rect) { defer { tripleBufferIndex = (tripleBufferIndex + 1) % uniformTripleBuffer.count } let uniformsBuffer = uniformTripleBuffer[tripleBufferIndex] let uniformsBufferPtr = UnsafeMutablePointer<Uniforms>(OpaquePointer(uniformsBuffer.contents())) uniformsBufferPtr.pointee.transform = context.transform uniformsBufferPtr.pointee.contentSize = SIMD2<Float>(Float(context.deviceSize.width), Float(context.deviceSize.height)) uniformsBufferPtr.pointee.patternSize = SIMD2<Float>(Float(context.brushPattern.width), Float(context.brushPattern.height)) let vertexes = self.vertices(for: rect) assert(vertexes.count == rectangularVertexCount) let vertexBuffer = rectVertexTripleBuffer[tripleBufferIndex] let vertexArrayPtr = UnsafeMutablePointer<Vertex>(OpaquePointer(vertexBuffer.contents())) let vertexArray = UnsafeMutableBufferPointer<Vertex>(start: vertexArrayPtr, count: vertexes.count) (0 ..< vertexes.count).forEach { vertexArray[$0] = vertexes[$0] } let commandBuffer = context.makeCommandBuffer() let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: context.renderPassDescriptor)! encoder.pushDebugGroup("pattern filling") encoder.setRenderPipelineState(self.renderPipelineState) encoder.setFrontFacing(.clockwise) // commandEncoder.setCullMode(.back) encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(uniformsBuffer, offset: 0, index: 1) encoder.setFragmentTexture(context.shadingTexture, index: 0) encoder.setFragmentTexture(context.brushPattern, index: 1) encoder.setFragmentSamplerState(self.shadingSamplerState, index: 0) encoder.setFragmentSamplerState(self.patternSamplerState, index: 1) encoder.setFragmentBuffer(uniformsBuffer, offset: 0, index: 0) encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertexes.count) encoder.popDebugGroup() encoder.endEncoding() commandBuffer.commit() } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromMTKTextureLoaderOption(_ input: MTKTextureLoader.Option) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalMTKTextureLoaderOptionDictionary(_ input: [String: Any]?) -> [MTKTextureLoader.Option: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (MTKTextureLoader.Option(rawValue: key), value)}) }
mit
d9b4cbf79a17028fc3ee202071d98a55
34.442857
132
0.737875
3.80911
false
false
false
false
nekowen/GeoHex3.swift
Example/Example/ViewController.swift
1
2431
// // ViewController.swift // GeoHex3.swift // // Created by nekowen on 2017/03/30. // License: MIT License // import UIKit import MapKit import GeoHex3Swift class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! fileprivate var polygons: [MKOverlay] = [] override func viewDidLoad() { super.viewDidLoad() self.drawPin() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func drawPin() { let coordinate = CLLocationCoordinate2D(latitude: 35.710063, longitude: 139.8107) let zone = GeoHex3.getZone(coordinate: coordinate, level: 7) let st = MKPointAnnotation() st.coordinate = zone.coordinate st.title = zone.code self.mapView.addAnnotation(st) self.mapView.selectAnnotation(st, animated: true) self.move(coordinate: zone.coordinate) } fileprivate func move(coordinate: CLLocationCoordinate2D) { var cr = mapView.region cr.center = coordinate cr.span = MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03) self.mapView.setRegion(cr, animated: true) } } extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolygonRenderer(overlay: overlay) renderer.strokeColor = UIColor.blue renderer.lineWidth = 1.0 return renderer } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { let nepoint = CGPoint(x: mapView.bounds.origin.x + mapView.bounds.size.width, y: mapView.bounds.origin.y) let swpoint = CGPoint(x: mapView.bounds.origin.x, y: mapView.bounds.origin.y + mapView.bounds.size.height) let ne = mapView.convert(nepoint, toCoordinateFrom: mapView) let sw = mapView.convert(swpoint, toCoordinateFrom: mapView) self.mapView.removeOverlays(self.polygons) let zones: [Zone] = GeoHex3.getZone(southWest: sw, northEast: ne, level: 7, buffer: false) self.polygons = zones.map { (zone) in let path = zone.polygon return MKPolygon(coordinates: path, count: path.count) } self.mapView.addOverlays(self.polygons) } }
mit
6c074ec7dfe16ebfe1daceeaa9219308
32.30137
114
0.658577
4.364452
false
false
false
false
ParsifalC/CPCollectionViewKit
Demos/CPCollectionViewTransitionDemo/CPCollectionViewTransitionDemo/CPViewController.swift
1
4039
// // CPViewController.swift // CPCollectionViewTransitionDemo // // Created by Parsifal on 2017/2/28. // Copyright © 2017年 Parsifal. All rights reserved. // import UIKit import CPCollectionViewKit class CPViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! let cellIdentifier = "CPCollectionViewCell" var dataArray = [(index: Int, color: UIColor)]() var fromLayout: UICollectionViewLayout! var toLayout: UICollectionViewLayout! var transitionManager: TransitionManager! var fromContentOffset = CGPoint(x: 0, y: 0) var toContentOffset = CGPoint(x: 0, y: 0) static func createViewController(fromLayout: UICollectionViewLayout, toLayout: UICollectionViewLayout) -> CPViewController { let sb = UIStoryboard.init(name: "Main", bundle: nil) let transitionViewController = sb.instantiateViewController(withIdentifier: "CPViewController") as! CPViewController transitionViewController.fromLayout = fromLayout transitionViewController.toLayout = toLayout return transitionViewController } override func viewDidLoad() { super.viewDidLoad() //Data Array for index in 0...19 { dataArray.append((index, randomColor())) } collectionView.setCollectionViewLayout(fromLayout, animated: false, completion: nil) } @IBAction func dismiss(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } func randomColor() -> UIColor { return UIColor(red: CGFloat(Double(arc4random_uniform(256))/255.0), green: CGFloat(Double(arc4random_uniform(256))/255.0), blue: CGFloat(Double(arc4random_uniform(256))/255.0), alpha: 1) } } extension CPViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) cell.backgroundColor = dataArray[indexPath.item].color return cell } } extension CPViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { fromContentOffset = collectionView.contentOffset if let contentOffset = (toLayout as? CollectionViewLayoutProtocol)?.contentOffsetFor(indexPath: indexPath) { toContentOffset = contentOffset } else if toLayout is UICollectionViewFlowLayout { let cellSize = (toLayout as! UICollectionViewFlowLayout).itemSize let y = floor(CGFloat(indexPath.item) / 3.0) * cellSize.height toContentOffset = CGPoint(x: 0, y: min(fabs(toLayout.collectionViewContentSize.height-collectionView.bounds.height), y)) } transitionManager = TransitionManager(duration: 0.6, collectionView: collectionView, toLayout: toLayout) transitionManager.startInteractiveTransition { self.collectionView.contentOffset = self.toContentOffset self.toLayout = self.fromLayout self.fromLayout = self.collectionView.collectionViewLayout } } func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout { let customTransitionLayout = CollectionViewTransitionLayout(currentLayout: fromLayout, nextLayout: toLayout) customTransitionLayout.fromContentOffset = fromContentOffset customTransitionLayout.toContentOffset = toContentOffset return customTransitionLayout } }
mit
28d431e48d2cc3013138020d30e73ee3
38.960396
206
0.699703
5.84081
false
false
false
false
Harley-xk/SimpleDataKit
Example/Pods/Comet/Comet/Extensions/Date+Comet.swift
1
5686
// // Date+Comet.swift // Comet // // Created by Harley on 2016/11/9. // // import Foundation public extension Date { public enum DateUnit { case year case month case day case hour case minute case second } /// 从日期字符串创建日期对象 public init?(string: String, format: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.current) { let formatter = DateFormatter() formatter.dateFormat = format formatter.timeZone = timeZone if let date = formatter.date(from: string) { self = date }else { return nil } } /// 将日期转换为指定格式的字符串 public func string(format: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.current) -> String { let formatter = DateFormatter() formatter.dateFormat = format formatter.timeZone = timeZone return formatter.string(from: self) } /// 转换为年月日的字符串 public func dateString() -> String { return string(format: "yyyy-MM-dd") } /// 日期计算,返回当前日期加上指定单位值之后的日期,会自动进位或减位 /// 返回计算后的新日期 public func add(_ value: Int, _ unit: DateUnit) -> Date { let component = unit.componentValue() let calendar = Calendar.current var components = calendar.dateComponents(DateUnit.all(), from: self) components.timeZone = TimeZone.current if let oriValue = components.value(for: component) { components.setValue(oriValue + value, for: component) } let date = calendar.date(from: components) return date ?? self } /// 将指定单位设置为指定的值,返回修改后的新日期 /// 如果设置的值大于当前单位的最大值或者小于最小值,会自动进位或减位 public func set(_ unit: DateUnit, to value: Int) -> Date { let component = unit.componentValue() let calendar = Calendar.current var components = calendar.dateComponents(DateUnit.all(), from: self) components.timeZone = TimeZone.current components.setValue(value, for: component) let date = calendar.date(from: components) return date ?? self } /// 忽略精确时间(时/分/秒)的日期 public var withoutTime: Date { let calendar = Calendar.current var components = calendar.dateComponents([.year, .month, .day], from: self) components.timeZone = TimeZone.current let date = calendar.date(from: components) return date ?? self } /// 某个单位的值 public func unit(_ unit: DateUnit) -> Int { let component = unit.componentValue() let calendar = Calendar.current var components = calendar.dateComponents([component], from: self) components.timeZone = TimeZone.current return components.value(for: component) ?? 0 } /// 周几,周日为0 public var weekday: Int { let calendar = Calendar.current var components = calendar.dateComponents([.weekday], from: self) components.timeZone = TimeZone.current return (components.weekday ?? 1) - 1 } // 两个日期相隔的分钟数 public func minutesSince(_ date: Date) -> Double { let timeInterval = timeIntervalSince(date) let minute = timeInterval / 60 return minute } // 两个日期相隔的小时数 public func hoursSince(_ date: Date) -> Double { let minute = minutesSince(date) return minute / 60 } /// 两个日期相隔的天数 /// /// - Parameters: /// - date: 与当前日期比较的日期 /// - withoutTime: 是否忽略精确的时分秒,可以启用该属性来比较两个日期的物理天数(即昨天、前天等) /// - Returns: 天数 public func daysSince(_ date: Date, withoutTime: Bool = false) -> Double { var date1 = self var date2 = date if withoutTime { date1 = self.withoutTime date2 = date.withoutTime } let hours = date1.hoursSince(date2) return hours / 24 } /// 判断两个日期是否在同一天内 public func isSameDay(as date: Date?) -> Bool { guard let date = date else { return false } let days = daysSince(date, withoutTime: true) return days == 0 } } public extension TimeZone { /// 中国时区(东8区) public static var china: TimeZone { return TimeZone(identifier: "Asia/Shanghai")! } // UTC 0 时区 public static var zero: TimeZone { return TimeZone(abbreviation: "UTC")! } } fileprivate extension Date.DateUnit { fileprivate func componentValue() -> Calendar.Component { switch self { case .year: return .year case .month: return .month case .day: return .day case .hour: return .hour case .minute: return .minute case .second: return .second } } fileprivate static func all() -> Set<Calendar.Component> { return [.year, .month, .day, .hour, . minute, .second] } } public extension Locale { /// 中国地区 public static var china: Locale { return Locale(identifier: "zh_Hans_CN") } /// 美国地区 public static var usa: Locale { return Locale(identifier: "es_US") } }
mit
83095842ccabcca50df0946999af1c7d
25.410256
113
0.584854
4.146538
false
false
false
false
mmremann/Hackathon
PushIt/PushIt/Model/DDPDay.swift
1
1384
// // DDPDay.swift // PushIt // // Created by Mann, Josh (US - Denver) on 9/25/15. // Copyright © 2015 Mann, Josh (US - Denver). All rights reserved. // import UIKit class DDPDay: NSObject { var id:NSNumber? var frequency:NSNumber? var totalNumberOfPushUpsToday:NSNumber? var date:NSDate? var percentageOfMax:NSNumber? //Memberwise initalizer init(dict:[String:AnyObject]) { super.init() self.updateWithDictionary(dict) } //MARK: NSCoding func updateWithDictionary(dict:[String:AnyObject]) { guard let newId = dict["max"] as? NSNumber, newFrequency = dict["startDate"] as? NSNumber, newtotalNumberOfPushUpsToday = dict["endDate"] as? NSNumber, newDate = dict["endDate"] as? NSDate, newPercentageOfMax = dict["percentageOfMax"] as? NSNumber else { print("Error reading Challenge Dict") return } id = newId frequency = newFrequency totalNumberOfPushUpsToday = newtotalNumberOfPushUpsToday date = newDate percentageOfMax = newPercentageOfMax } func dictionaryRepresentation() -> [String:AnyObject]? { let dict:[String:AnyObject]? = nil // create json dictionary return dict; } }
gpl-2.0
8182dfd55bc36c12543186fa6375bb8d
25.09434
73
0.591468
4.64094
false
false
false
false
aschwaighofer/swift
test/Frontend/Fingerprints/enum-fingerprint.swift
2
3447
// Test per-type-body fingerprints for enums // // ============================================================================= // Without the fingerprints // ============================================================================= // Establish status quo // RUN: %empty-directory(%t) // RUN: cp %S/Inputs/enum-fingerprint/* %t // RUN: cp %t/definesAB{-before,}.swift // Seeing weird failure on CI, so set the mod times // RUN: touch -t 200101010101 %t/*.swift // RUN: cd %t && %swiftc_driver -disable-type-fingerprints -enable-batch-mode -j2 -incremental -driver-show-incremental main.swift definesAB.swift usesA.swift usesB.swift -module-name main -output-file-map ofm.json >&output1 // only-run-for-debugging: cp %t/usesB.swiftdeps %t/usesB1.swiftdeps // Change one type, but uses of all types get recompiled // RUN: cp %t/definesAB{-after,}.swift // Seeing weird failure on CI, so ensure that definesAB.swift is newer // RUN: touch -t 200201010101 %t/* // RUN: touch -t 200101010101 %t/*.swift // RUN: touch -t 200301010101 %t/definesAB.swift // RUN: cd %t && %swiftc_driver -disable-type-fingerprints -enable-batch-mode -j2 -incremental -driver-show-incremental main.swift definesAB.swift usesA.swift usesB.swift -module-name main -output-file-map ofm.json >&output2 // Save for debugging: // only-run-for-debugging: cp %t/usesB.swiftdeps %t/usesB1.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-MAINAB-RECOMPILED %s < %t/output2 // CHECK-MAINAB-RECOMPILED: Queuing (initial): {compile: definesAB.o <= definesAB.swift} // CHECK-MAINAB-RECOMPILED: Queuing because of dependencies discovered later: {compile: usesA.o <= usesA.swift} // CHECK-MAINAB-RECOMPILED: Queuing because of dependencies discovered later: {compile: usesB.o <= usesB.swift} // ============================================================================= // With the fingerprints // ============================================================================= // Establish status quo // RUN: %empty-directory(%t) // RUN: cp %S/Inputs/enum-fingerprint/* %t // RUN: cp %t/definesAB{-before,}.swift // Seeing weird failure on CI, so set the mod times // RUN: touch -t 200101010101 %t/*.swift // RUN: cd %t && %swiftc_driver -enable-batch-mode -j2 -incremental -driver-show-incremental main.swift definesAB.swift usesA.swift usesB.swift -module-name main -output-file-map ofm.json >&output3 // only-run-for-debugging: cp %t/usesB.swiftdeps %t/usesB3.swiftdeps // Change one type, only uses of that type get recompiled // RUN: cp %t/definesAB{-after,}.swift // Seeing weird failure on CI, so ensure that definesAB.swift is newer // RUN: touch -t 200201010101 %t/* // RUN: touch -t 200101010101 %t/*.swift // RUN: touch -t 200301010101 %t/definesAB.swift // RUN: cd %t && %swiftc_driver -enable-batch-mode -j2 -incremental -driver-show-incremental main.swift definesAB.swift usesA.swift usesB.swift -module-name main -output-file-map ofm.json >&output4 // only-run-for-debugging: cp %t/usesB.swiftdeps %t/usesB4.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-MAINB-RECOMPILED %s < %t/output4 // CHECK-MAINB-RECOMPILED-NOT: Queuing because of dependencies discovered later: {compile: usesB.o <= usesB.swift} // CHECK-MAINB-RECOMPILED: Queuing because of dependencies discovered later: {compile: usesA.o <= usesA.swift} // CHECK-MAINB-RECOMPILED-NOT: Queuing because of dependencies discovered later: {compile: usesB.o <= usesB.swift}
apache-2.0
8c807a5858c15f668ede9b945942504e
42.632911
226
0.663185
3.694534
false
false
false
false
joerocca/GitHawk
Pods/Apollo/Sources/Apollo/Promise.swift
3
5934
import Dispatch public func whenAll<Value>(_ promises: [Promise<Value>], notifyOn queue: DispatchQueue = .global()) -> Promise<[Value]> { return Promise { (fulfill, reject) in let group = DispatchGroup() for promise in promises { group.enter() promise.andThen { value in group.leave() }.catch { error in reject(error) } } group.notify(queue: queue) { fulfill(promises.map { $0.result!.value! }) } } } public func firstly<T>(_ body: () throws -> Promise<T>) -> Promise<T> { do { return try body() } catch { return Promise(rejected: error) } } public final class Promise<Value> { private let lock = Mutex() private var state: State<Value> private typealias ResultHandler<Value> = (Result<Value>) -> Void private var resultHandlers: [ResultHandler<Value>] = [] public init(resolved result: Result<Value>) { state = .resolved(result) } public init(fulfilled value: Value) { state = .resolved(.success(value)) } public init(rejected error: Error) { state = .resolved(.failure(error)) } public init(_ body: () throws -> Value) { do { let value = try body() state = .resolved(.success(value)) } catch { state = .resolved(.failure(error)) } } public init(_ body: (_ fulfill: @escaping (Value) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void) { state = .pending do { try body(self.fulfill, self.reject) } catch { self.reject(error) } } public var isPending: Bool { return lock.withLock { state.isPending } } public var result: Result<Value>? { return lock.withLock { switch state { case .pending: return nil case .resolved(let result): return result } } } public func wait() { let semaphore = DispatchSemaphore(value: 0) whenResolved { result in semaphore.signal() } semaphore.wait() } public func await() throws -> Value { let semaphore = DispatchSemaphore(value: 0) var result: Result<Value>? = nil whenResolved { result = $0 semaphore.signal() } semaphore.wait() return try result!.valueOrError() } @discardableResult public func andThen(_ whenFulfilled: @escaping (Value) throws -> Void) -> Promise<Value> { return Promise<Value> { fulfill, reject in whenResolved { result in switch result { case .success(let value): do { try whenFulfilled(value) fulfill(value) } catch { reject(error) } case .failure(let error): reject(error) } } } } @discardableResult public func `catch`(_ whenRejected: @escaping (Error) throws -> Void) -> Promise<Value> { return Promise<Value> { fulfill, reject in whenResolved { result in switch result { case .success(let value): fulfill(value) case .failure(let error): do { try whenRejected(error) reject(error) } catch { reject(error) } } } } } @discardableResult public func finally(_ whenResolved: @escaping () -> Void) -> Promise<Value> { self.whenResolved { _ in whenResolved() } return self } public func map<T>(_ transform: @escaping (Value) throws -> T) -> Promise<T> { return Promise<T> { fulfill, reject in whenResolved { result in switch result { case .success(let value): do { fulfill(try transform(value)) } catch { reject(error) } case .failure(let error): reject(error) } } } } public func flatMap<T>(_ transform: @escaping (Value) throws -> Promise<T>) -> Promise<T> { return Promise<T> { fulfill, reject in whenResolved { result in switch result { case .success(let value): do { try transform(value).andThen(fulfill).catch(reject) } catch { reject(error) } case .failure(let error): reject(error) } } } } public func on(queue: DispatchQueue) -> Promise<Value> { return Promise<Value> { fulfill, reject in whenResolved { result in switch result { case .success(let value): queue.async { fulfill(value) } case .failure(let error): queue.async { reject(error) } } } } } private func fulfill(_ value: Value) { resolve(.success(value)) } private func reject(_ error: Error) { resolve(.failure(error)) } private func resolve(_ result: Result<Value>) { lock.withLock { guard state.isPending else { return } state = .resolved(result) for handler in resultHandlers { handler(result) } resultHandlers = [] } } private func whenResolved(_ handler: @escaping ResultHandler<Value>) { lock.withLock { // If the promise has been resolved and there are no existing result handlers, // there is no need to append the handler to the array first. if case .resolved(let result) = state, resultHandlers.isEmpty { handler(result) } else { resultHandlers.append(handler) } } } } private enum State<Value> { case pending case resolved(Result<Value>) var isPending: Bool { if case .pending = self { return true } else { return false } } } extension State: CustomStringConvertible { var description: String { switch self { case .pending: return "Promise(Pending)" case .resolved(let result): return "Promise(\(result))" } } }
mit
44a76aead46209b320279340e2c13339
21.823077
121
0.561004
4.353632
false
false
false
false
cuappdev/podcast-ios
old/Podcast/PlayerEpisodeDetailView.swift
1
9233
// // EpisodeDetailView.swift // Podcast // // Created by Mark Bryan on 2/19/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit import MarqueeLabel protocol PlayerEpisodeDetailDelegate: class { func playerEpisodeDetailViewDidDrag(sender: UIPanGestureRecognizer) func playerEpisodeDetailViewDidTapArtwork() } class PlayerEpisodeDetailView: UIView, UIGestureRecognizerDelegate { var expandedArtwork: Bool = true var episodeArtworkImageView: ImageView! var episodeTitleLabel: MarqueeLabel! var dateLabel: UILabel! var descriptionTextView: UITextView! var seeMoreButton: UIButton! let marginSpacing: CGFloat = 24 let trailingSpacing: CGFloat = 18 let artworkY: CGFloat = 10 let artworkLargeDimension: CGSize = CGSize(width: 250, height: 250) let artworkSmallDimension: CGSize = CGSize(width: 48, height: 48) let artworkLargeWidthMultiplier: CGFloat = 0.7 let artworkSmallWidthMultiplier: CGFloat = 0.12 let episodeTitleLabelHeight: CGFloat = 24 let episodeTitleTopOffset: CGFloat = 25 let dateLabelYSpacing: CGFloat = 8 let dateLabelHeight: CGFloat = 18 let descriptionTextViewTopOffset: CGFloat = 10 let descriptionTextViewShowMoreTopOffset: CGFloat = 19 let descriptionTextViewMarginSpacing: CGFloat = 18 let recommendButtonSpacing: CGFloat = 22.5 let bottomSpacing: CGFloat = 28.5 let episodeTitleShowMoreSpacing: CGFloat = 12 let dateLabelShowMoreTopOffset: CGFloat = 5.5 let seeMoreButtonWidth: CGFloat = 100 let seeMoreButtonHeight: CGFloat = 20 let episodeTitleSpeed: CGFloat = 60 let episodeTitleTrailingBuffer: CGFloat = 10 let episodeTitleAnimationDelay: CGFloat = 2 weak var delegate: PlayerEpisodeDetailDelegate? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear episodeArtworkImageView = ImageView(frame: CGRect(x: 0, y: 0, width: artworkLargeDimension.width, height: artworkLargeDimension.height)) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didPressSeriesArtwork)) episodeArtworkImageView.isUserInteractionEnabled = true episodeArtworkImageView.addGestureRecognizer(tapGestureRecognizer) addSubview(episodeArtworkImageView) episodeTitleLabel = MarqueeLabel(frame: .zero) episodeTitleLabel.font = ._16RegularFont() episodeTitleLabel.textColor = .charcoalGrey episodeTitleLabel.numberOfLines = 1 episodeTitleLabel.lineBreakMode = .byTruncatingTail episodeTitleLabel.speed = .rate(episodeTitleSpeed) episodeTitleLabel.trailingBuffer = episodeTitleTrailingBuffer episodeTitleLabel.type = .continuous episodeTitleLabel.fadeLength = episodeTitleSpeed episodeTitleLabel.tapToScroll = false episodeTitleLabel.holdScrolling = true episodeTitleLabel.animationDelay = episodeTitleAnimationDelay addSubview(episodeTitleLabel) dateLabel = UILabel(frame: .zero) dateLabel.font = ._12RegularFont() dateLabel.textColor = .slateGrey dateLabel.numberOfLines = 5 dateLabel.lineBreakMode = .byWordWrapping addSubview(dateLabel) descriptionTextView = UITextView(frame: .zero) descriptionTextView.isEditable = false descriptionTextView.font = ._14RegularFont() descriptionTextView.textColor = .charcoalGrey descriptionTextView.showsVerticalScrollIndicator = false descriptionTextView.backgroundColor = .clear descriptionTextView.textContainerInset = UIEdgeInsets.zero descriptionTextView.textContainer.lineFragmentPadding = 0 addSubview(descriptionTextView) seeMoreButton = Button() seeMoreButton.frame = CGRect(x: 0, y: 0, width: seeMoreButtonWidth, height: seeMoreButtonHeight) seeMoreButton.setTitleColor(.sea, for: .normal) seeMoreButton.titleLabel?.textAlignment = .center seeMoreButton.titleLabel?.font = ._14RegularFont() seeMoreButton.contentVerticalAlignment = .center seeMoreButton.contentHorizontalAlignment = .center seeMoreButton.addTarget(self, action: #selector(showMoreTapped), for: .touchUpInside) addSubview(seeMoreButton) let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(viewDragged(_:))) panGestureRecognizer.delegate = self addGestureRecognizer(panGestureRecognizer) } override func layoutSubviews() { super.layoutSubviews() // see if the description can fit with the large player view - if so, hide the "See more" button let descriptionHeight = descriptionTextView.attributedText.height(withConstrainedWidth: frame.width - 2 * trailingSpacing) seeMoreButton.isHidden = (descriptionTextView.frame.minY + descriptionHeight) < seeMoreButton.frame.minY && expandedArtwork episodeArtworkImageView.addCornerRadius(height: episodeArtworkImageView.frame.height) } func updateUIForEpisode(episode: Episode) { episodeArtworkImageView.setImageAsynchronouslyWithDefaultImage(url: episode.largeArtworkImageURL) episodeTitleLabel.text = episode.title dateLabel.text = episode.dateTimeLabelString descriptionTextView.attributedText = episode.attributedDescription.toEpisodeDescriptionStyle() expandedArtwork = true episodeTitleLabel.holdScrolling = false layoutUI() } func layoutUI() { if expandedArtwork { episodeArtworkImageView.snp.remakeConstraints({ make in make.top.equalToSuperview().offset(artworkY).priority(999) make.width.equalToSuperview().multipliedBy(artworkLargeWidthMultiplier) make.height.equalTo(episodeArtworkImageView.snp.width) make.centerX.equalToSuperview() }) episodeTitleLabel.snp.remakeConstraints({ make in make.top.equalTo(episodeArtworkImageView.snp.bottom).offset(episodeTitleTopOffset) make.leading.trailing.equalToSuperview().inset(marginSpacing) make.height.equalTo(episodeTitleLabelHeight) }) dateLabel.snp.remakeConstraints({ make in make.leading.trailing.equalToSuperview().inset(marginSpacing) make.top.equalTo(episodeTitleLabel.snp.bottom) make.height.equalTo(dateLabelHeight) }) } else { episodeArtworkImageView.snp.remakeConstraints({ make in make.width.equalToSuperview().multipliedBy(artworkSmallWidthMultiplier) make.height.equalTo(episodeArtworkImageView.snp.width) make.leading.equalTo(marginSpacing) make.top.equalToSuperview().offset(artworkY) }) episodeTitleLabel.snp.remakeConstraints({ make in make.top.equalTo(episodeArtworkImageView.snp.top) make.leading.equalTo(episodeArtworkImageView.snp.trailing).offset(episodeTitleShowMoreSpacing) make.trailing.equalToSuperview().inset(trailingSpacing) }) dateLabel.snp.remakeConstraints({ make in make.top.equalTo(episodeTitleLabel.snp.bottom) make.bottom.greaterThanOrEqualTo(episodeArtworkImageView.snp.bottom) make.leading.equalTo(episodeArtworkImageView.snp.trailing).offset(episodeTitleShowMoreSpacing) make.trailing.equalToSuperview().inset(trailingSpacing) }) } descriptionTextView.snp.remakeConstraints({ make in make.top.equalTo(dateLabel.snp.bottom).offset(descriptionTextViewTopOffset) make.leading.trailing.equalToSuperview().inset(marginSpacing) make.bottom.lessThanOrEqualToSuperview().inset(descriptionTextViewShowMoreTopOffset) }) seeMoreButton.snp.remakeConstraints { make in make.trailing.equalTo(descriptionTextView.snp.trailing) make.height.equalTo(seeMoreButtonHeight) make.bottom.equalToSuperview() } descriptionTextView.isScrollEnabled = !expandedArtwork seeMoreButton.setTitle(expandedArtwork ? "Show More" : "Show Less", for: .normal) layoutIfNeeded() } @objc func viewDragged(_ sender: UIPanGestureRecognizer) { delegate?.playerEpisodeDetailViewDidDrag(sender: sender) } @objc func showMoreTapped() { expandedArtwork = !expandedArtwork UIView.animate(withDuration: 0.5) { self.layoutUI() } } @objc func didPressSeriesArtwork() { delegate?.playerEpisodeDetailViewDidTapArtwork() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view != seeMoreButton } }
mit
4ff49358c24e6852268b5160fa792078
42.753555
144
0.696274
5.71995
false
false
false
false
GYLibrary/A_Y_T
GYVideo/GYVideo/View/GYVideoCell.swift
1
12026
// // GYVideoCell.swift // GYVideo // // Created by ZGY on 2017/2/7. // Copyright © 2017年 GYJade. All rights reserved. // // Author: Airfight // My GitHub: https://github.com/airfight // My Blog: http://airfight.github.io/ // My Jane book: http://www.jianshu.com/users/17d6a01e3361 // Current Time: 2017/2/7 15:54 // GiantForJade: Efforts to do my best // Real developers ship. import UIKit import SDWebImage class GYVideoCell: UITableViewCell { ///背景图片 var bgImage: UIImageView? /// 标题 var titleLb: GYLabel? ///开始播放按钮 var startBtn: UIButton? ///视频总时间 var timeLb: GYLabel? ///播放次数 var countLb: GYLabel? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) createSubViews() } func reloadData(_ model: VideoModel) { titleLb?.text = model.title bgImage?.sd_setImage(with:URL(string:model.cover!), placeholderImage: nil) var timeText = "00:00" if model.length != nil { timeText = String(Int(model.length!)! / 60) + ":" + String(Int(model.length!)! % 60) } timeLb?.text = timeText countLb?.text = model.playCount } fileprivate func createSubViews() { if titleLb == nil { titleLb = GYLabel() titleLb?.textAlignment = .center self.contentView.addSubview(titleLb!) //如果通过代码来设置Autolayout约束, 必须给需要设置约束的视图禁用autoresizing titleLb?.translatesAutoresizingMaskIntoConstraints = false // let width:NSLayoutConstraint = NSLayoutConstraint(item: titleLb!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: self.frame.width) let height:NSLayoutConstraint = NSLayoutConstraint(item: titleLb!, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 20) titleLb?.addConstraints([height]) let top:NSLayoutConstraint = NSLayoutConstraint(item: titleLb!, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 10) let left:NSLayoutConstraint = NSLayoutConstraint(item: titleLb!, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 20) let right:NSLayoutConstraint = NSLayoutConstraint(item: titleLb!, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -20) self.contentView.addConstraints([top,left,right]) } if bgImage == nil { bgImage = UIImageView() bgImage?.backgroundColor = UIColor.red self.contentView.addSubview(bgImage!) bgImage?.translatesAutoresizingMaskIntoConstraints = false // let top: NSLayoutConstraint = NSLayoutConstraint(item: bgImage!, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 40) let top: NSLayoutConstraint = NSLayoutConstraint(item: bgImage!, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.titleLb!, attribute: NSLayoutAttribute.bottomMargin, multiplier: 1.0, constant: 10) let bootom: NSLayoutConstraint = NSLayoutConstraint(item: bgImage!, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -30) let left: NSLayoutConstraint = NSLayoutConstraint(item: bgImage!, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 0) let right: NSLayoutConstraint = NSLayoutConstraint(item: bgImage!, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0) // 因为titleLb的frame未确定,所以调用titleLb会导致crash,需要调取superView titleLb?.superview?.addConstraint(top) self.contentView.addConstraints([bootom,left,right]) } if startBtn == nil { startBtn = UIButton() startBtn?.setBackgroundImage(UIImage(named:"video_play_btn_bg.png"), for: UIControlState.normal) self.contentView.addSubview(startBtn!) startBtn?.translatesAutoresizingMaskIntoConstraints = false let centerX = NSLayoutConstraint(item: startBtn!, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: bgImage, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 1) let centerY = NSLayoutConstraint(item: startBtn!, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: bgImage, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 1) bgImage?.superview?.addConstraints([centerX,centerY]) let width = NSLayoutConstraint(item: startBtn!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 64) let height = NSLayoutConstraint(item: startBtn!, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 64) startBtn?.addConstraints([width,height]) } self.contentView.addSubview(timeSumLb) timeSumLb.translatesAutoresizingMaskIntoConstraints = false var left = NSLayoutConstraint(item: timeSumLb, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 10) var bootom = NSLayoutConstraint(item: timeSumLb, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -5) self.contentView.addConstraints([left,bootom]) var width = NSLayoutConstraint(item: timeSumLb, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 25) var height = NSLayoutConstraint(item: timeSumLb, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 25) timeSumLb.addConstraints([width,height]) if timeLb == nil { timeLb = GYLabel() self.contentView.addSubview(timeLb!) timeLb?.text = "00:00" timeLb?.translatesAutoresizingMaskIntoConstraints = false let left = NSLayoutConstraint(item: timeLb!, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: timeSumLb, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 8) let centerY = NSLayoutConstraint(item: timeLb!, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: timeSumLb, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 1) timeSumLb.superview?.addConstraints([left,centerY]) let width = NSLayoutConstraint(item: timeLb!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 30) let height = NSLayoutConstraint(item: timeLb!, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 22) timeLb?.addConstraints([width,height]) } self.contentView.addSubview(readLb) readLb.translatesAutoresizingMaskIntoConstraints = false left = NSLayoutConstraint(item: readLb, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.timeLb!, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 8) timeLb?.superview?.addConstraints([left]) bootom = NSLayoutConstraint(item: readLb, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -5) self.contentView.addConstraints([bootom]) width = NSLayoutConstraint(item: readLb, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 25) height = NSLayoutConstraint(item: readLb, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 25) readLb.addConstraints([width,height]) if countLb == nil { countLb = GYLabel() self.contentView.addSubview(countLb!) countLb?.translatesAutoresizingMaskIntoConstraints = false countLb?.text = "0" let left = NSLayoutConstraint(item: countLb!, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: readLb, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 8) let centerY = NSLayoutConstraint(item: countLb!, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: readLb, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 1) readLb.superview?.addConstraints([left,centerY]) let width = NSLayoutConstraint(item: countLb!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 30) let height = NSLayoutConstraint(item: countLb!, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 22) countLb?.addConstraints([width,height]) } } /// 视频总时间 private lazy var timeSumLb: UIImageView = { let image = UIImageView() image.image = UIImage(named: "time") return image }() /// 观看次数 private lazy var readLb: UIImageView = { let image = UIImageView() image.image = UIImage(named: "playcount") return image }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
7b88f2868e9c6ca7b96ceefccf710fe6
53.223744
253
0.680337
5.284824
false
false
false
false
WeMadeCode/ZXPageView
Example/Pods/SwifterSwift/Sources/SwifterSwift/UIKit/UITableViewExtensions.swift
1
7681
// // UITableViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Properties public extension UITableView { /// SwifterSwift: Index path of last row in tableView. var indexPathForLastRow: IndexPath? { return indexPathForLastRow(inSection: lastSection) } /// SwifterSwift: Index of last section in tableView. var lastSection: Int { return numberOfSections > 0 ? numberOfSections - 1 : 0 } } // MARK: - Methods public extension UITableView { /// SwifterSwift: Number of all rows in all sections of tableView. /// /// - Returns: The count of all rows in the tableView. func numberOfRows() -> Int { var section = 0 var rowCount = 0 while section < numberOfSections { rowCount += numberOfRows(inSection: section) section += 1 } return rowCount } /// SwifterSwift: IndexPath for last row in section. /// /// - Parameter section: section to get last row in. /// - Returns: optional last indexPath for last row in section (if applicable). func indexPathForLastRow(inSection section: Int) -> IndexPath? { guard section >= 0 else { return nil } guard numberOfRows(inSection: section) > 0 else { return IndexPath(row: 0, section: section) } return IndexPath(row: numberOfRows(inSection: section) - 1, section: section) } /// Reload data with a completion handler. /// /// - Parameter completion: completion handler to run after reloadData finishes. func reloadData(_ completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } /// SwifterSwift: Remove TableFooterView. func removeTableFooterView() { tableFooterView = nil } /// SwifterSwift: Remove TableHeaderView. func removeTableHeaderView() { tableHeaderView = nil } /// SwifterSwift: Scroll to bottom of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). func scrollToBottom(animated: Bool = true) { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) setContentOffset(bottomOffset, animated: animated) } /// SwifterSwift: Scroll to top of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint.zero, animated: animated) } /// SwifterSwift: Dequeue reusable UITableViewCell using class name /// /// - Parameter name: UITableViewCell type /// - Returns: UITableViewCell object with associated class name. func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view") } return cell } /// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath /// /// - Parameters: /// - name: UITableViewCell type. /// - indexPath: location of cell in tableView. /// - Returns: UITableViewCell object with associated class name. func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view") } return cell } /// SwifterSwift: Dequeue reusable UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type /// - Returns: UITableViewHeaderFooterView object with associated class name. func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T { guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewHeaderFooterView for \(String(describing: name)), make sure the view is registered with table view") } return headerFooterView } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameters: /// - nib: Nib file used to create the header or footer view. /// - name: UITableViewHeaderFooterView type. func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) { register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) { register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameter name: UITableViewCell type func register<T: UITableViewCell>(cellWithClass name: T.Type) { register(T.self, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameters: /// - nib: Nib file used to create the tableView cell. /// - name: UITableViewCell type. func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) { register(nib, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell with .xib file using only its corresponding class. /// Assumes that the .xib filename and cell class has the same name. /// /// - Parameters: /// - name: UITableViewCell type. /// - bundleClass: Class in which the Bundle instance will be based on. func register<T: UITableViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) { let identifier = String(describing: name) var bundle: Bundle? if let bundleName = bundleClass { bundle = Bundle(for: bundleName) } register(UINib(nibName: identifier, bundle: bundle), forCellReuseIdentifier: identifier) } /// SwifterSwift: Check whether IndexPath is valid within the tableView /// /// - Parameter indexPath: An IndexPath to check /// - Returns: Boolean value for valid or invalid IndexPath func isValidIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section) } /// SwifterSwift: Safely scroll to possibly invalid IndexPath /// /// - Parameters: /// - indexPath: Target IndexPath to scroll to /// - scrollPosition: Scroll position /// - animated: Whether to animate or not func safeScrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) { guard indexPath.section < numberOfSections else { return } guard indexPath.row < numberOfRows(inSection: indexPath.section) else { return } scrollToRow(at: indexPath, at: scrollPosition, animated: animated) } } #endif
mit
c2827d68a28c3ad64c18d30abe8b5114
37.984772
149
0.670052
5.126836
false
false
false
false
soxjke/Redux-ReactiveSwift
Example/Simple-Weather-App/Simple-Weather-App/Views/WeatherView.swift
1
2236
// // WeatherView.swift // Simple-Weather-App // // Created by Petro Korienev on 10/24/17. // Copyright © 2017 Sigma Software. All rights reserved. // import UIKit import ReactiveCocoa import ReactiveSwift import Result class WeatherView: UIView { private struct Const { static let cellIdentifier = "WeatherFeatureCell" static let cellHeight: CGFloat = 44 } @IBOutlet private weak var tableView: UITableView! fileprivate var weatherFeatures: [WeatherFeatureCellKind] = [] static func fromNib() -> WeatherView { guard let view = Bundle.main.loadNibNamed("WeatherView", owner: nil)?.first as? WeatherView else { fatalError("No bunlde for: \(String(describing: self))") } return view } func reload(with weatherFeatures: [WeatherFeatureCellKind]) { self.weatherFeatures = weatherFeatures tableView.reloadData() } override func awakeFromNib() { super.awakeFromNib() tableView.register(UINib.init(nibName: Const.cellIdentifier, bundle: nil), forCellReuseIdentifier: Const.cellIdentifier) } } extension WeatherView: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return weatherFeatures[indexPath.row].needsStaticHeight() ? Const.cellHeight : UITableViewAutomaticDimension } } extension WeatherView: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return weatherFeatures.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: Const.cellIdentifier, for: indexPath) as? WeatherFeatureCell else { fatalError("Wrong type of table view cell") } cell.set(feature: weatherFeatures[indexPath.row]) return cell } } extension Reactive where Base == WeatherView { var weatherFeatures: BindingTarget<[WeatherFeatureCellKind]> { return makeBindingTarget { $0.reload(with: $1) } } }
mit
7ab9be91d692474c27652ba6756ed725
32.863636
138
0.696644
5.056561
false
false
false
false
multinerd/Mia
Mia/Extensions/Foundation/Date/Date+Time.swift
1
541
import Foundation extension Date { public var hasTime: Bool { let components = self.components return !(components.hour! == 0 && components.minute! == 0 && components.second! == 0 && components.nanosecond! == 0) } public var timeOfDay: TimeOfDay { guard hasTime else { return .none } switch components.hour! { case 5..<12: return .morning case 12..<17: return .afternoon case 17..<22: return .evening default: return .night } } }
mit
554568b59690e23f8879f943fa4715da
23.590909
124
0.567468
4.434426
false
false
false
false
avenwu/swift_basic
IntroductionToAlgrithms/SwiftBasic.swift
1
2542
// // SwiftBasic.swift // IntroductionToAlgrithms // // Created by aven wu on 14/10/26. // Copyright (c) 2014年 avenwu. All rights reserved. // import Foundation func executeDemoUsage(){ let A = "A" println(A) var i = 1 var f:Float = 2 var d:Double = 2 let text = "Interger is \(i), Float is \(f), Double is \(d).\nString is \(A)" println(text) let array = ["A", "B", "C", 1] println("array = \(array)") let dic = [ "name":"Zhang san", "email":"[email protected]" ] println("dictionary = \(dic)") var emptyArray = [String]() var emptyDictionary = [String:String]() println("empty array = \(emptyArray), empty dictionary = \(emptyDictionary)") for element in array { println("Element=\(element), name=\(element.className)") if element == "A" { println("Bingo, \(element) is hit") } } var optionalString: String? = "Default value is Hello World" optionalString = "Hello Swift" println(optionalString) optionalString = nil println(optionalString) var vegetable = "red pepper" vegetable = "watercress pepper" switch vegetable { case "celery": println("celery hit") case let x where x.hasPrefix("watercress"): println("customer") case let x where x.hasSuffix("pepper"): println("x=\(x)") default: println("default") } var loop = 0 for i in 0..<5 { println(i) } println("-----") for i in 0...5 { println(i) } func testFunction(name:String, day:String)->String{ return "hello \(name), today is \(day)" } func calculateStatics(scores:[Int])->(max:Int, min:Int, sum:Int){ var max = scores[0] var min = scores[0] var sum = 0 for i in scores { if i > max { max = i } if i < min { min = i } sum+=i } return (max, min, sum) } println(testFunction("Java","2014/10/26")) let result = calculateStatics([1,2,3,4,5,6]) println("result=\(result), max = \(result.max), min = \(result.min), sum = \(result.sum)") println("max = \(result.0)") func sumof(numbers:Int...)->Int{ var sum = 0 for i in numbers { sum += i } return sum } println(sumof(1,2,3)) var temp = [3,5,2,1,9,0] let a = sorted(temp){$0>$1} println(a) }
apache-2.0
e745eb825a91e3d1ed6e03a20dc7cf2d
23.669903
94
0.520472
3.746313
false
false
false
false
grafiti-io/SwiftCharts
SwiftCharts/Views/ChartViewAnimators.swift
3
3650
// // ChartViewAnimators.swift // SwiftCharts // // Created by ischuetz on 02/09/16. // Copyright © 2016 ivanschuetz. All rights reserved. // import UIKit public struct ChartViewAnimatorsSettings { public let animDelay: Float public let animDuration: Float public let animDamping: CGFloat public let animInitSpringVelocity: CGFloat public init(animDelay: Float = 0, animDuration: Float = 0.3, animDamping: CGFloat = 0.7, animInitSpringVelocity: CGFloat = 1) { self.animDelay = animDelay self.animDuration = animDuration self.animDamping = animDamping self.animInitSpringVelocity = animInitSpringVelocity } public func copy(_ animDelay: Float? = nil, animDuration: Float? = nil, animDamping: CGFloat? = nil, animInitSpringVelocity: CGFloat? = nil) -> ChartViewAnimatorsSettings { return ChartViewAnimatorsSettings( animDelay: animDelay ?? self.animDelay, animDuration: animDuration ?? self.animDuration, animDamping: animDamping ?? self.animDamping, animInitSpringVelocity: animInitSpringVelocity ?? self.animInitSpringVelocity ) } public func withoutDamping() -> ChartViewAnimatorsSettings { return copy(animDelay, animDuration: animDuration, animDamping: 1, animInitSpringVelocity: animInitSpringVelocity) } } /// Runs a series of animations on a view open class ChartViewAnimators { open var animDelay: Float = 0 open var animDuration: Float = 10.3 open var animDamping: CGFloat = 0.4 open var animInitSpringVelocity: CGFloat = 0.5 fileprivate let animators: [ChartViewAnimator] fileprivate let onFinishAnimations: (() -> Void)? fileprivate let onFinishInverts: (() -> Void)? fileprivate let view: UIView fileprivate let settings: ChartViewAnimatorsSettings fileprivate let invertSettings: ChartViewAnimatorsSettings public init(view: UIView, animators: ChartViewAnimator..., settings: ChartViewAnimatorsSettings = ChartViewAnimatorsSettings(), invertSettings: ChartViewAnimatorsSettings? = nil, onFinishAnimations: (() -> Void)? = nil, onFinishInverts: (() -> Void)? = nil) { self.view = view self.animators = animators self.onFinishAnimations = onFinishAnimations self.onFinishInverts = onFinishInverts self.settings = settings self.invertSettings = invertSettings ?? settings } open func animate() { for animator in animators { animator.prepare(view) } animate(settings, animations: { for animator in self.animators { animator.animate(self.view) } }, onFinish: { self.onFinishAnimations?() }) } open func invert() { animate(invertSettings, animations: { for animator in self.animators { animator.invert(self.view) } }, onFinish: { self.onFinishInverts?() }) } fileprivate func animate(_ settings: ChartViewAnimatorsSettings, animations: @escaping () -> Void, onFinish: @escaping () -> Void) { UIView.animate(withDuration: TimeInterval(settings.animDuration), delay: TimeInterval(settings.animDelay), usingSpringWithDamping: settings.animDamping, initialSpringVelocity: settings.animInitSpringVelocity, options: UIViewAnimationOptions(), animations: { animations() }, completion: {finished in if finished { onFinish() } }) } }
apache-2.0
70c44c6d4ce249fdb7c1fe34262204c6
35.49
265
0.654426
5.554033
false
false
false
false
JeanVinge/UICollectionViewToolsSwift
UICollectionViewToolsSwift/ViewController/ViewController.swift
1
1796
// // ViewController.swift // UICollectionViewToolsSwift // // Created by Jean Vinge on 29/07/16. // Copyright © 2016 Jean Vinge. All rights reserved. // import UIKit import ObjectMapper class ViewController: UIViewController { // //MARK: Var and outlet declaration // @IBOutlet weak var collectionView: UICollectionView! @IBOutlet var collectionViewData: CollectionViewData! // //MARK: View life cicle methods // override func viewDidLoad() { super.viewDidLoad() self.collectionView.registerNib(CollectionViewCell.self) self.collectionView.registerNib(CollectionViewTwoCell.self) self.collectionView.registerNib(CollectionViewHeaderCell.self, forSuplementaryViewOfKind: UICollectionElementKindSectionHeader) if let path = Bundle.main.path(forResource: "flickr", ofType: "json") { do { let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: Data.ReadingOptions.mappedIfSafe) do { let array = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray let flickr = Mapper<FlickrModel>().mapArray(JSONObject: array) self.collectionViewData.list = flickr self.collectionView.reloadData() } catch let error as NSError { // error.description print(error.description) } } catch let error as NSError { // error.description print(error.description) } } } }
mit
941b3fa3413ef7e76b0a9c647a9196f4
31.636364
153
0.591086
5.716561
false
false
false
false
cotkjaer/SilverbackFramework
SilverbackFramework/EKEventStore.swift
1
9931
// // EKEventStore.swift // SilverbackFramework // // Created by Christian Otkjær on 25/08/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import Foundation import EventKit public extension EKEventStore { //MARK: Access private func asyncDoWhenAccessIsGrantedToEntityType( entityType: EKEntityType, completionHandler: () -> (), errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler ) { requestAccessToEntityType(entityType, completion: { (granted, error) -> () in if granted { // Ensure that call-back is done on main queue dispatch_async(dispatch_get_main_queue(), { completionHandler() }) } else { // Ensure that call-back is done on main queue dispatch_async(dispatch_get_main_queue(), { if let theError = error { errorHandler?(theError) } else { errorHandler?(NSError(domain: "EKEventStore", code: 1234, description: "Permission was not granted for \(entityType)")) } }) } }) } //MARK: Calendars public func fetchCalendarsForEntityType(entityType: EKEntityType, completionHandler: ([EKCalendar]) -> (), errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { asyncDoWhenAccessIsGrantedToEntityType(entityType, completionHandler: { completionHandler(self.calendarsForEntityType(entityType)) }) { (error) -> () in errorHandler?(NSError(domain: "EKEventStore", code: 1235, description: "Could not fetch calendars for EntityType \(entityType)", reason: "Access Denied", underlyingError: error)) } } public func fetchEventCalendars(completionHandler: ([EKCalendar]) -> (), errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { fetchCalendarsForEntityType(EKEntityType.Event, completionHandler: completionHandler, errorHandler: errorHandler) } public func fetchReminderCalendars(completionHandler: ([EKCalendar]) -> (), errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { fetchCalendarsForEntityType(EKEntityType.Reminder, completionHandler: completionHandler, errorHandler: errorHandler) } //MARK: - Events //MARK: Fetch public func doFetchEventsInCalendar(eventCalendar: EKCalendar, firstDate: NSDate?, lastDate: NSDate?) -> [EKEvent]? { let from = firstDate ?? NSDate() - 1.year let to = lastDate ?? NSDate() + 3.year let calendars = [eventCalendar] let predicate = predicateForEventsWithStartDate(from, endDate: to, calendars: calendars) return eventsMatchingPredicate(predicate) } public func asyncFetchEventsInCalendar(calendar: EKCalendar, firstDate: NSDate?, lastDate: NSDate?, completionHandler: ((events: [EKEvent]) -> ())? = nil, errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { asyncDoWhenAccessIsGrantedToEntityType(EKEntityType.Event, completionHandler: { if let events = self.doFetchEventsInCalendar(calendar, firstDate: firstDate, lastDate: lastDate) { completionHandler?(events: events) } else { completionHandler?(events: []) } }, errorHandler: { (error) -> () in errorHandler?(NSError(domain: "EKEventStore", code: 1236, description: "Could not fetch events in calendar \(calendar)", reason: "Access Denied", underlyingError: error)) }) } //MARK: Create public func asyncCreateAllDayEventInCalendar( calendar: EKCalendar, title: String, availability: EKEventAvailability = .Free, date: NSDate, notes: String, completionHandler: ((event: EKEvent) -> ())? = nil, errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { asyncCreateEventInCalendar(calendar, title: title, availability: availability, allDay: true, startDate: date, endDate: date, notes: notes, completionHandler: completionHandler, errorHandler: errorHandler) } public func createEventInCalendar( calendar: EKCalendar, title: String, availability: EKEventAvailability = .Free, allDay: Bool, startDate: NSDate, endDate: NSDate, notes: String) -> EKEvent { let event = EKEvent(eventStore: self) event.title = title event.availability = availability event.allDay = allDay event.startDate = startDate event.endDate = endDate event.notes = notes event.calendar = calendar event.alarms = nil return event } public func asyncCreateEventInCalendar( calendar: EKCalendar, title: String, availability: EKEventAvailability = .Free, allDay: Bool, startDate: NSDate, endDate: NSDate, notes: String, completionHandler: ((event: EKEvent) -> ())? = nil, errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { let event = createEventInCalendar(calendar, title: title, availability: availability, allDay: allDay, startDate: startDate, endDate: endDate, notes: notes) do { try saveEvent(event, span: .ThisEvent) completionHandler?(event: event) } catch let e as NSError { errorHandler?(e) } } //MARK: Remove public func asyncRemoveEventWithIdentifier(eventIdentifier: String, completionHandler: ((removed: Bool) -> ()) = { (removed) -> () in }, errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { asyncDoWhenAccessIsGrantedToEntityType(EKEntityType.Event, completionHandler: { if let event = self.eventWithIdentifier(eventIdentifier) { do { try self.removeEvent(event, span: .FutureEvents, commit: true) completionHandler(removed: true) } catch let error as NSError { errorHandler?(NSError(domain: "Event Kit", code: 1201, description: "Could not remove event \(event.title) in calendar \(event.calendar.title)", underlyingError: error)) completionHandler(removed: false) } catch { errorHandler?(NSError(domain: "Event Kit", code: 1201, description: "Could not remove event \(event.title) in calendar \(event.calendar.title)")) completionHandler(removed: false) } } }, errorHandler: errorHandler) } //MARK: Save public func asyncSaveEvent(event: EKEvent, completionHandler: ((saved: Bool) -> ()) = { (removed) -> () in }, errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler ) { asyncDoWhenAccessIsGrantedToEntityType(.Event, completionHandler: { do { try self.saveEvent(event, span: .FutureEvents, commit: true) completionHandler(saved: true) } catch let e as NSError { errorHandler?(NSError(domain: "Event Kit", code: 1201, description: "Could not save event \(event.title) in calendar \(event.calendar.title)", underlyingError: e)) completionHandler(saved: false) } catch { errorHandler?(NSError(domain: "Event Kit", code: 1201, description: "Could not save event \(event.title) in calendar \(event.calendar.title)")) completionHandler(saved: false) } }, errorHandler: errorHandler) } //MARK: Alarms public func asyncRemoveAllAlarmsFromEvent(event: EKEvent, completionHandler: ((saved: Bool) -> ()) = { _ in }, errorHandler:((NSError) -> ())? = NSError.defaultAsyncErrorHandler) { if let alarms = event.alarms { debugPrint("removing \(alarms.count) alarms") for alarm in alarms { event.removeAlarm(alarm) debugPrint("removed alarm: \(alarm)") } self.asyncSaveEvent(event, completionHandler: completionHandler, errorHandler: errorHandler) } else { completionHandler(saved: false) } } } extension EKCalendarType: CustomDebugStringConvertible { public var debugDescription : String { switch self { case .Local: return "Local" case .CalDAV: return "CalDAV" case .Exchange: return "Exchange" case .Birthday: return "Birthday" case .Subscription: return "Subscription" } } } //extension EKCalendarType : Equatable { } // //public func == (lhs: EKCalendarType, rhs: EKCalendarType) -> Bool //{ // return lhs.rawValue == rhs.rawValue //}
mit
d1b709e3aa70899b5a9130762f7570ea
35.5
212
0.555298
5.669903
false
false
false
false
solszl/Shrimp500px
Shrimp500px/Model/User.swift
1
1599
// // User.swift // Shrimp500px // // Created by 振亮 孙 on 16/3/2. // Copyright © 2016年 papa.studio. All rights reserved. // import Foundation import ObjectMapper struct User: Mappable, Equatable { /// 用户ID var id: Int? /// 用户名 var username: String? /// 头像连接 var avatar: String? /// 封面 var coverURL: String? /// 姓 var firstName: String? /// 名 var lastName: String? /// 全称 var fullname: String? /// 照片数量 var photos_count: Int? /// 画廊数量 var galleries_count: Int? /// 性别 var sex:Int = Sex.Female.rawValue /// 是否正在关注 var isFollowing: Bool = false /// 好友数量 var friendCount: Int? /// 关注了多少人 var followers_count: Int? init?(_ map: Map) { mapping(map) } mutating func mapping(map: Map) { self.id <- map["id"] self.username <- map["username"] self.firstName <- map["firstname"] self.lastName <- map["lastname"] self.fullname <- map["fullname"] self.photos_count <- map["photos_count"] self.galleries_count <- map["galleries_count"] self.sex <- map["sex"] self.isFollowing <- map["following"] self.friendCount <- map["friends_count"] self.followers_count <- map["followers_count"] } } private enum Sex:Int { case Female = 0 case Male = 1 } func ==(lhs: User, rhs: User) -> Bool { return lhs.id == rhs.id }
mit
18f3d9b085ab20c3572d764e4faef2a5
18.101266
55
0.536472
3.70516
false
false
false
false
Caktuspace/iTunesCover
iTunesCover/iTunesCover/Classes/Common/Categories/UIImageView+download.swift
1
777
// // UIImage+download.swift // iTunesCover // // Created by Quentin Metzler on 20/12/15. // Copyright © 2015 LocalFitness. All rights reserved. // import Foundation extension UIImageView { func downloadedFrom(link link:String, contentMode mode: UIViewContentMode) { guard let url = NSURL(string: link) else {return} contentMode = mode NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, _, error) -> Void in guard let data = data where error == nil, let image = UIImage(data: data) else { return } dispatch_async(dispatch_get_main_queue(), { self.image = image }) }).resume() } }
gpl-2.0
d32311aeec27cc7dc77cddb9a8444230
27.777778
106
0.573454
4.564706
false
false
false
false
xedin/swift
test/Constraints/bridging.swift
1
17866
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a type from another module. We only allow this for a // few specific types, like String. extension LazyFilterSequence.Iterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'Iterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterSequence.Iterator { let result: LazyFilterSequence.Iterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { func hash(into hasher: inout Hasher) {} func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' does not conform to 'AnyObject'}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt as Any] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // FIXME: Another awful diagnostic. return d == d // expected-error{{'<Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool' requires that 'NotEquatable' conform to 'Equatable'}} // expected-note @-1 {{requirement from conditional conformance of 'Dictionary<Int, NotEquatable>' to 'Equatable'}} // expected-error @-2 {{type 'NotEquatable' does not conform to protocol 'Equatable'}} // expected-note @-3{{requirement specified as 'NotEquatable' : 'Equatable'}} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 _ = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: For floating point numbers use truncatingRemainder instead}} var inferDouble2 = 1 / 3 / 3.0 let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error@-1 {{generic parameter 'K' could not be inferred}} // expected-error@-2 {{generic parameter 'V' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[Any]'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Array<Element>, Array<Element>), (Other, Self), (Self, Other)}} var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{cannot convert value of type 'NSString?' to expected argument type 'String?'}}{{21-21= as String?}} var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}}{{43-43= as NSString}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}}{{39-39= as NSString?}} var s4: String = ns ?? "str" // expected-error{{cannot convert value of type 'NSString' to specified type 'String'}}{{31-31= as String}} var s5: String = (ns ?? "str") as String // fixed version } // Make sure more complicated cast has correct parenthesization func castMoreComplicated(anInt: Int?) { let _: (NSObject & NSCopying)? = anInt // expected-error{{cannot convert value of type 'Int?' to specified type '(NSObject & NSCopying)?'}}{{41-41= as (NSObject & NSCopying)?}} } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } func rdar28856049(_ nsma: NSMutableArray) { _ = nsma as? [BridgedClass] _ = nsma as? [BridgedStruct] _ = nsma as? [BridgedClassSub] } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{does not conform to 'AnyObject'}} z = b z = c // expected-error{{does not conform to 'AnyObject'}} expected-note {{cast 'Any' to 'AnyObject'}} {{8-8= as AnyObject}} z = d // expected-error{{does not conform to 'AnyObject'}} z = e z = f z = g z = h // expected-error{{does not conform to 'AnyObject'}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y }
apache-2.0
be59f3f2c4371ddb3e38457ba5d40848
46.515957
236
0.69316
4.054925
false
false
false
false
CGDevHusky92/CGMatrix
CGMatrix/ViewController.swift
1
4203
// // ViewController.swift // AutoTest // // Created by Chase Gorectke on 11/7/14. // Copyright (c) 2014 Revision Works, LLC. All rights reserved. // import UIKit class ViewController: UIViewController, CGDataMatrixDelegate, CGDataMatrixDataSource { @IBOutlet var testView: CGDataMatrixView! var columnNames: [String]! var rowNames: [String]! var matrix: CGMatrix<String>! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. testView.delegate = self testView.dataSource = self self.setupArrays() var nib: UINib = UINib(nibName: "TestCollectionViewCell", bundle: nil) testView.registerNib(nib, forSingleHeaderCellWithReuseIdentifier: "SingleIdentifier") testView.registerNib(nib, forColumnCellWithReuseIdentifier: "ColumnIdentifier") testView.registerNib(nib, forRowCellWithReuseIdentifier: "RowIdentifier") testView.registerNib(nib, forMatrixCellWithReuseIdentifier: "MatrixIdentifier") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) testView.reloadData() } func setupArrays() { columnNames = [ "Alyssa", "Chase", "Darcy", "Marvin", "Nathan", "Robert" ] rowNames = testView.generateArrayWithStartingTime(9, andEndTime: 16.5, withInterval: 0.75) matrix = CGMatrix(rows: rowNames.count, columns: columnNames.count) for row in 0...rowNames.count { for col in 0...columnNames.count { matrix[row, col] = "\(row), \(col)" } } } /* CGDataMatrix Delegate */ func dataMatrix(matrixView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { println("Matrix Object Selected...") } func dataMatrixSeparatorSize() -> Float { return 10.0 } /* CGDataMatrix Data Source */ func numberOfRowsInDataMatrix(dataMatrixView: CGDataMatrixView) -> Int { return rowNames.count } func numberOfColumnsInDataMatrix(dataMatrixView: CGDataMatrixView) -> Int { return columnNames.count } func dataMatrixCellForSingleHeader(singleCollectionView: UICollectionView) -> UICollectionViewCell { let indexPath: NSIndexPath = NSIndexPath(forItem: 0, inSection: 0) var cell: TestCollectionViewCell = singleCollectionView.dequeueReusableCellWithReuseIdentifier("SingleIdentifier", forIndexPath: indexPath) as! TestCollectionViewCell cell.textLabel.text = ""; return cell } func dataMatrix(columnCollectionView: UICollectionView, cellForColumnAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell: TestCollectionViewCell = columnCollectionView.dequeueReusableCellWithReuseIdentifier("ColumnIdentifier", forIndexPath: indexPath) as! TestCollectionViewCell cell.textLabel.text = columnNames[indexPath.row]; return cell } func dataMatrix(rowCollectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell: TestCollectionViewCell = rowCollectionView.dequeueReusableCellWithReuseIdentifier("RowIdentifier", forIndexPath: indexPath) as! TestCollectionViewCell cell.textLabel.text = rowNames[indexPath.row]; return cell } func dataMatrix(matrixCollectionView: UICollectionView, cellForMatrixItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell: TestCollectionViewCell = matrixCollectionView.dequeueReusableCellWithReuseIdentifier("MatrixIdentifier", forIndexPath: indexPath) as! TestCollectionViewCell let coord: (Int, Int) = testView.coordinateForIndexPath(indexPath) let text = matrix[coord.0, coord.1] cell.textLabel.text = text return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
b1cfcc209ecd2785d8380bea7eb89611
35.232759
174
0.682846
5.581673
false
true
false
false
RadioBear/CalmKit
CalmKit/Animators/BRBCalmKitArcAnimator.swift
1
2815
// // BRBCalmKitArcAnimator.swift // CalmKit // // Copyright (c) 2016 RadioBear // // 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 class BRBCalmKitArcAnimator: BRBCalmKitAnimator { func setupAnimation(inLayer layer : CALayer, withSize size : CGSize, withColor color : UIColor) { let beginTime = CACurrentMediaTime() let frame: CGRect = CGRectInset(CGRectMake(0.0, 0.0, size.width, size.height), 2.0, 2.0) let radius: CGFloat = frame.width * 0.5 let center: CGPoint = CGPointMake(frame.midX, frame.midY) let arc = CALayer() arc.frame = CGRectMake(0.0, 0.0, size.width, size.height) arc.backgroundColor = color.CGColor arc.anchorPoint = CGPointMake(0.5, 0.5) let path = CGPathCreateMutable() CGPathAddArc(path, nil, center.x, center.y, radius, 0.0, ((CGFloat(M_PI) * 2.0) / 360.0) * 300.0, false) let mask = CAShapeLayer() mask.frame = CGRectMake(0.0, 0.0, size.width, size.height) mask.path = path mask.strokeColor = UIColor.blackColor().CGColor mask.fillColor = UIColor.clearColor().CGColor mask.lineWidth = 2.0 mask.anchorPoint = CGPointMake(0.5, 0.5) arc.mask = mask; let anim = CAKeyframeAnimation(keyPath: "transform.rotation.z") anim.removedOnCompletion = false anim.repeatCount = HUGE anim.duration = 0.8 anim.beginTime = beginTime anim.timeOffset = NSDate.timeIntervalSinceReferenceDate() anim.keyTimes = [0.0, 0.5, 1.0] anim.values = [0.0, M_PI, M_PI * 2.0] layer.addSublayer(arc) arc.addAnimation(anim, forKey:"calmkit-anim") } }
mit
a6d8656383fbc64c31d233fc083142b2
40.397059
112
0.662522
4.195231
false
false
false
false
huonw/swift
test/SILGen/objc_generic_class.swift
1
2048
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo // Although we don't ever expose initializers and methods of generic classes // to ObjC yet, a generic subclass of an ObjC class must still use ObjC // deallocation. // CHECK-NOT: sil hidden @$SSo7GenericCfd // CHECK-NOT: sil hidden @$SSo8NSObjectCfd class Generic<T>: NSObject { var x: Int = 10 // CHECK-LABEL: sil hidden @$S18objc_generic_class7GenericCfD : $@convention(method) <T> (@owned Generic<T>) -> () { // CHECK: bb0({{%.*}} : @owned $Generic<T>): // CHECK: } // end sil function '$S18objc_generic_class7GenericCfD' // CHECK-LABEL: sil hidden [thunk] @$S18objc_generic_class7GenericCfDTo : $@convention(objc_method) <T> (Generic<T>) -> () { // CHECK: bb0([[SELF:%.*]] : @unowned $Generic<T>): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[NATIVE:%.*]] = function_ref @$S18objc_generic_class7GenericCfD // CHECK: apply [[NATIVE]]<T>([[SELF_COPY]]) // CHECK: } // end sil function '$S18objc_generic_class7GenericCfDTo' deinit { // Don't blow up when 'self' is referenced inside an @objc deinit method // of a generic class. <rdar://problem/16325525> self.x = 0 } } // CHECK-NOT: sil hidden @$S18objc_generic_class7GenericCfd // CHECK-NOT: sil hidden @$SSo8NSObjectCfd // CHECK-LABEL: sil hidden @$S18objc_generic_class11SubGeneric1CfD : $@convention(method) <U, V> (@owned SubGeneric1<U, V>) -> () { // CHECK: bb0([[SELF:%.*]] : @owned $SubGeneric1<U, V>): // CHECK: [[SUPER_DEALLOC:%.*]] = objc_super_method [[SELF]] : $SubGeneric1<U, V>, #Generic.deinit!deallocator.foreign : <T> (Generic<T>) -> () -> (), $@convention(objc_method) <τ_0_0> (Generic<τ_0_0>) -> () // CHECK: [[SUPER:%.*]] = upcast [[SELF:%.*]] : $SubGeneric1<U, V> to $Generic<Int> // CHECK: apply [[SUPER_DEALLOC]]<Int>([[SUPER]]) class SubGeneric1<U, V>: Generic<Int> { }
apache-2.0
1191a30e33dd433e3d76a2fabf383f17
46.581395
215
0.625122
3.294686
false
false
false
false
xivol/Swift-CS333
playgrounds/extras/location/annotationView/annotationView/ViewController.swift
3
5496
// // ViewController.swift // annotationView // // Created by Илья Лошкарёв on 15.04.17. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import UIKit import MapKit import Contacts class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() if CLLocationManager.locationServicesEnabled() { locationManager.requestWhenInUseAuthorization() mapView.delegate = self mapView.showsUserLocation = true } else { showError(NSError(domain: "Location Services Unavailiable", code: 0, userInfo: [:])) } initMMCS() } func initMMCS() { CLGeocoder().reverseGeocodeLocation(MMCSAnnotation.location){ placemarks, error in guard let places = placemarks else { fatalError("Empty geocoder result") } guard error == nil else { self.showError(error!) return } for place in places { let marker = MMCSAnnotation(placemark: place) self.mapView.addAnnotation(marker) } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation !== mapView.userLocation { let pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin") pin.pinTintColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) pin.canShowCallout = true let infoButton = UIButton(type: .detailDisclosure) pin.rightCalloutAccessoryView = infoButton let navButton = UIButton(type: .system) navButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50) navButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) navButton.setImage(#imageLiteral(resourceName: "Car").withRenderingMode(.alwaysTemplate), for: .normal) navButton.backgroundColor = navButton.tintColor navButton.tintColor = UIColor.white pin.leftCalloutAccessoryView = navButton return pin } return nil } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let annotation = view.annotation! as? MMCSAnnotation { if control === view.leftCalloutAccessoryView { annotation.mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]) } else { UIApplication.shared.open(annotation.url, options: [:], completionHandler: nil) } } } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { let region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1000, 1000) mapView.setRegion(region, animated: true) // remove outdated route for overlay in mapView.overlays { mapView.remove(overlay) } // create route request let routeRequest = MKDirectionsRequest() routeRequest.source = MKMapItem(placemark: MKPlacemark(coordinate: userLocation.coordinate)) routeRequest.destination = MKMapItem(placemark: MKPlacemark(coordinate: MMCSAnnotation.location.coordinate)) routeRequest.transportType = .automobile routeRequest.requestsAlternateRoutes = false let directions = MKDirections(request: routeRequest) directions.calculate { response, error in guard error == nil else { self.showError(error!) return } if let route = response?.routes.first { mapView.addOverlays([route.polyline], level: .aboveRoads) mapView.setVisibleMapRect(route.polyline.boundingMapRect * 1.5, animated: true) } } } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKPolyline { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1) renderer.lineWidth = 4.0 return renderer } return MKOverlayRenderer() } func showError(_ error: Error) { let error = error as NSError let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } func * ( _ rect: MKMapRect, _ scale: Double) -> MKMapRect { let center = MKMapPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height / 2) let size = MKMapSizeMake(rect.size.width * scale, rect.size.height * scale) let origin = MKMapPointMake(center.x-size.width/2, center.y-size.height/2) return MKMapRectMake(origin.x, origin.y, size.width, size.height) }
mit
d1ea8f5af8cc7966e099a64e796ff0fc
36.993056
134
0.618534
5.230402
false
false
false
false