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
dfucci/iTunesSearch
iTunesSearch/SearchResultsViewController.swift
1
4877
// // ViewController.swift // iTunesSearch // // Created by Davide Fucci on 19/10/14. // Copyright (c) 2014 Davide Fucci. All rights reserved. // import UIKit class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol { @IBOutlet var tblResults:UITableView? let kCellIdentifier: String = "SearchResultCell" var api : APIController? var albums = [Album]() var imageCache = [String : UIImage]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. api = APIController(delegate: self) UIApplication.sharedApplication().networkActivityIndicatorVisible = true api!.searchItunesFor("Beatles") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell let album = self.albums[indexPath.row] //var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary // Add a check to make sure this exists // let cellText: String? = rowData["trackName"] as? String cell.textLabel?.text = album.title cell.imageView?.image = UIImage(named: "Blank52") // Get the formatted price string for display in the subtitle let formattedPrice = album.price // Jump in to a background thread to get the image for this item // Grab the artworkUrl60 key to get an image URL for the app's thumbnail let urlString = album.thumbnailImageURL // Check our image cache for the existing key. This is just a dictionary of UIImages //var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage var image = self.imageCache[urlString] if(image == nil) { // If the image does not exist, we need to download it var imgURL: NSURL = NSURL(string: urlString) // Download an NSData representation of the image at the URL let request: NSURLRequest = NSURLRequest(URL: imgURL) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in if error == nil { image = UIImage(data: data) // Store the image in to our cache self.imageCache[urlString] = image dispatch_async(dispatch_get_main_queue(), { if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) { cellToUpdate.imageView?.image = image } }) } else { println("Error: \(error.localizedDescription)") } }) } else { dispatch_async(dispatch_get_main_queue(), { if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) { cellToUpdate.imageView?.image = image } }) } cell.detailTextLabel?.text = formattedPrice return cell } func didReceiveAPIResults(results: NSDictionary) { var resultsArr: NSArray = results["results"] as NSArray dispatch_async(dispatch_get_main_queue(), { self.albums = Album.albumsWithJSON(resultsArr) self.tblResults!.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false }) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var detailsViewController: DetailsViewController = segue.destinationViewController as DetailsViewController var albumIndex = tblResults!.indexPathForSelectedRow()!.row var selectedAlbum = self.albums[albumIndex] detailsViewController.album = selectedAlbum } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1) UIView.animateWithDuration(0.25, animations: { cell.layer.transform = CATransform3DMakeScale(1,1,1) }) } }
apache-2.0
73f0ed01bd16ab95651cd48c1ab6a831
37.706349
185
0.620463
5.599311
false
false
false
false
adrfer/swift
test/IRGen/select_enum_optimized.swift
20
2580
// RUN: %target-swift-frontend -primary-file %s -O -disable-llvm-optzns -emit-ir | FileCheck %s enum NoPayload { case E0 case E1 case E2 case E3 } // Check if the code of a select_num is a simple int cast and not a switch. // CHECK-LABEL: define {{.*}}selectDirect // CHECK: %1 = zext i2 %0 to i32 // CHECK: ret i32 %1 @inline(never) func selectDirect(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 case .E2: return 2 case .E3: return 3 } } // CHECK-LABEL: define {{.*}}selectNegOffset // CHECK: %1 = zext i2 %0 to i32 // CHECK: %2 = add i32 %1, -6 // CHECK: ret i32 %2 @inline(never) func selectNegOffset(e: NoPayload) -> Int32 { switch e { case .E0: return -6 case .E1: return -5 case .E2: return -4 case .E3: return -3 } } // CHECK-LABEL: define {{.*}}selectPosOffset // CHECK: %1 = zext i2 %0 to i32 // CHECK: %2 = add i32 %1, 3 // CHECK: ret i32 %2 @inline(never) func selectPosOffset(e: NoPayload) -> Int32 { switch e { case .E0: return 3 case .E1: return 4 case .E2: return 5 case .E3: return 6 } } // Following functions contain select_enums, which cannot be generated as a // simple conversion. // CHECK-LABEL: define {{.*}}selectWithDefault // CHECK: switch i2 // CHECK: ret @inline(never) func selectWithDefault(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 default: return 2 } } // CHECK-LABEL: define {{.*}}selectNonContiguous // CHECK: switch i2 // CHECK: ret @inline(never) func selectNonContiguous(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 case .E2: return 3 case .E3: return 4 } } var gg : Int32 = 10 // CHECK-LABEL: define {{.*}}selectNonConstant // CHECK: switch i2 // CHECK: ret @inline(never) func selectNonConstant(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 case .E2: return gg case .E3: return 4 } } // CHECK-LABEL: define {{.*}}selectTuple // CHECK: switch i2 // CHECK: ret @inline(never) func selectTuple(e: NoPayload) -> (Int32, Int32) { switch e { case .E0: return (0, 1) case .E1: return (1, 2) case .E2: return (2, 3) case .E3: return (3, 4) } } // CHECK-LABEL: define {{.*}}selectNonInt // CHECK: switch i2 // CHECK: ret @inline(never) func selectNonInt(e: NoPayload) -> String { switch e { case .E0: return "a" case .E1: return "ab" case .E2: return "abc" case .E3: return "abcd" } }
apache-2.0
c96a8dd93eda65a6831175e57120f79d
15.125
95
0.601938
2.844542
false
false
false
false
wangela/wittier
wittier/ViewControllers/ComposeViewController.swift
1
3384
// // ComposeViewController.swift // wittier // // Created by Angela Yu on 9/26/17. // Copyright © 2017 Angela Yu. All rights reserved. // import UIKit @objc protocol ComposeViewControllerDelegate { @objc optional func composeViewController(composeViewController: ComposeViewController, tweeted string: String) } class ComposeViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var composeTextView: UITextView! @IBOutlet weak var counterLabel: UILabel! weak var delegate: ComposeViewControllerDelegate? var new: Bool = true override func viewDidLoad() { super.viewDidLoad() let cancelButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(onCancelButton(_:))) let twitterBlue = UIColor(red: 29/255, green: 161/255, blue: 242/255, alpha: 1.0) cancelButton.tintColor = twitterBlue navigationItem.leftBarButtonItem = cancelButton new = true composeTextView.delegate = self composeTextView.clearsOnInsertion = true // composeTextView.inputAccessoryView = Bundle.main.loadNibNamed("ComposeAccessoryView", owner: self, options: nil) as! ComposeAccessoryView? } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) composeTextView.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { if new { composeTextView.text = "Write here" composeTextView.textColor = UIColor.lightGray DispatchQueue.main.async { self.composeTextView.selectedRange = NSRange(location: 0, length: 0) } } return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if new == true { composeTextView.text = "" composeTextView.textColor = UIColor.black new = false } return true } func textViewDidChange(_ textView: UITextView) { let length = composeTextView.text.count let charsLeft = 140 - length counterLabel.text = String(charsLeft) if charsLeft < 20 { counterLabel.textColor = UIColor.red } else { counterLabel.textColor = UIColor.darkGray } } func onCancelButton(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func onTweetButton(_ sender: Any) { guard let tweetText = composeTextView.text else { print("nil tweet, canceling") dismiss(animated: true, completion: nil) return } delegate?.composeViewController?(composeViewController: self, tweeted: tweetText) } /* // 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
fca045fccb72c20ecff412928d41d691
31.84466
149
0.647354
5.302508
false
false
false
false
kstaring/swift
test/stdlib/RangeDiagnostics.swift
1
13155
//===--- RangeDiagnostics.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-parse-verify-swift import StdlibUnittest func typeInference_Comparable<C : Comparable>(v: C) { do { var range = v..<v expectType(Range<C>.self, &range) } do { var range = v...v expectType(ClosedRange<C>.self, &range) } do { let r1: Range<C> = v...v // expected-error {{cannot convert value of type 'ClosedRange<C>' to specified type 'Range<C>'}} let r2: ClosedRange<C> = v..<v // expected-error {{cannot convert value of type 'Range<C>' to specified type 'ClosedRange<C>'}} let r3: CountableRange<C> = v..<v // expected-error {{type 'C' does not conform to protocol '_Strideable'}} let r4: CountableClosedRange<C> = v...v // expected-error {{type 'C' does not conform to protocol '_Strideable'}} let r5: CountableRange<C> = v...v // expected-error {{type 'C' does not conform to protocol '_Strideable'}} let r6: CountableClosedRange<C> = v..<v // expected-error {{type 'C' does not conform to protocol '_Strideable'}} } } func typeInference_Strideable<S : Strideable>(v: S) { do { var range = v..<v expectType(Range<S>.self, &range) } do { var range = v...v expectType(ClosedRange<S>.self, &range) } do { let r1: Range<S> = v...v // expected-error {{cannot convert value of type 'ClosedRange<S>' to specified type 'Range<S>'}} let r2: ClosedRange<S> = v..<v // expected-error {{cannot convert value of type 'Range<S>' to specified type 'ClosedRange<S>'}} let r3: CountableRange<S> = v..<v // expected-error {{type 'S.Stride' does not conform to protocol 'SignedInteger'}} let r4: CountableClosedRange<S> = v...v // expected-error {{type 'S.Stride' does not conform to protocol 'SignedInteger'}} let r5: CountableRange<S> = v...v // expected-error {{type 'S.Stride' does not conform to protocol 'SignedInteger'}} let r6: CountableClosedRange<S> = v..<v // expected-error {{type 'S.Stride' does not conform to protocol 'SignedInteger'}} } } func typeInference_StrideableWithSignedIntegerStride<S : Strideable>(v: S) where S.Stride : SignedInteger { do { var range = v..<v expectType(CountableRange<S>.self, &range) } do { var range = v...v expectType(CountableClosedRange<S>.self, &range) } do { let _: Range<S> = v..<v } do { let _: ClosedRange<S> = v...v } do { let _: Range<S> = v...v // expected-error {{cannot convert value of type 'CountableClosedRange<S>' to specified type 'Range<S>'}} let _: ClosedRange<S> = v..<v // expected-error {{cannot convert value of type 'CountableRange<S>' to specified type 'ClosedRange<S>'}} let _: CountableRange<S> = v...v // expected-error {{cannot convert value of type 'CountableClosedRange<S>' to specified type 'CountableRange<S>'}} let _: CountableClosedRange<S> = v..<v // expected-error {{cannot convert value of type 'CountableRange<S>' to specified type 'CountableClosedRange<S>'}} } } // Check how type inference works with a few commonly used types. func typeInference_commonTypes() { // --------------------------------------------- // operator '..<' // --------------------------------------------- do { var range = 1..<10 expectType(CountableRange<Int>.self, &range) } do { var range = UInt(1)..<10 expectType(CountableRange<UInt>.self, &range) } do { var range = Int8(1)..<10 expectType(CountableRange<Int8>.self, &range) } do { var range = UInt8(1)..<10 expectType(CountableRange<UInt8>.self, &range) } do { var range = 1.0..<10.0 expectType(Range<Double>.self, &range) } do { var range = Float(1.0)..<10.0 expectType(Range<Float>.self, &range) } do { var range = "a"..<"z" expectType(Range<String>.self, &range) } do { var range = Character("a")..<"z" expectType(Range<Character>.self, &range) } do { var range = UnicodeScalar("a")..<"z" expectType(Range<UnicodeScalar>.self, &range) } do { let s = "" var range = s.startIndex..<s.endIndex expectType(Range<String.Index>.self, &range) } // --------------------------------------------- // operator '...' // --------------------------------------------- do { var range = 1...10 expectType(CountableClosedRange<Int>.self, &range) } do { var range = UInt(1)...10 expectType(CountableClosedRange<UInt>.self, &range) } do { var range = Int8(1)...10 expectType(CountableClosedRange<Int8>.self, &range) } do { var range = UInt8(1)...10 expectType(CountableClosedRange<UInt8>.self, &range) } do { var range = 1.0...10.0 expectType(ClosedRange<Double>.self, &range) } do { var range = Float(1.0)...10.0 expectType(ClosedRange<Float>.self, &range) } do { var range = "a"..."z" expectType(ClosedRange<String>.self, &range) } do { var range = Character("a")..."z" expectType(ClosedRange<Character>.self, &range) } do { var range = UnicodeScalar("a")..."z" expectType(ClosedRange<UnicodeScalar>.self, &range) } do { let s = "" var range = s.startIndex...s.endIndex expectType(ClosedRange<String.Index>.self, &range) } } func disallowSubscriptingOnIntegers() { // FIXME: swift-3-indexing-model: decide what to do with the following QoI. // The previous implementation was imposing an ABI burden. // The point of this test is to check that we don't allow indexing // Range<Int> et al with Int outside a generic context, to prevent the // problem that r[0] will be invalid when 0 is not contained int he // range. // Many of these error messages are terrible. If the test starts // failing because the error message improves, obviously, update the // test! do { var r0 = 10..<100 var r1 = UInt(10)..<100 var r2 = 10...100 var r3 = UInt(10)...100 expectType(CountableRange<Int>.self, &r0) expectType(CountableRange<UInt>.self, &r1) expectType(CountableClosedRange<Int>.self, &r2) expectType(CountableClosedRange<UInt>.self, &r3) r0[0] // expected-error {{ambiguous use of 'subscript'}} r1[0] // expected-error {{ambiguous use of 'subscript'}} r2[0] // expected-error {{cannot convert value of type 'Int' to expected argument type 'Range<ClosedRangeIndex<_>>'}} r3[0] // expected-error {{cannot convert value of type 'Int' to expected argument type 'Range<ClosedRangeIndex<_>>'}} r0[UInt(0)] // expected-error {{cannot subscript a value of type 'CountableRange<Int>' with an index of type 'UInt'}} expected-note {{overloads for 'subscript' exist}} r1[UInt(0)] // expected-error {{ambiguous use of 'subscript'}} r2[UInt(0)] // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Range<ClosedRangeIndex<_>>'}} r3[UInt(0)] // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Range<ClosedRangeIndex<_>>'}} r0[0..<4] // expected-error {{ambiguous use of 'subscript'}} r1[0..<4] // expected-error {{ambiguous use of 'subscript'}} r2[0..<4] // expected-error {{cannot convert call result type 'CountableRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} r3[0..<4] // expected-error {{cannot convert call result type 'CountableRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} (10..<100)[0] // expected-error {{ambiguous use of 'subscript'}} (UInt(10)...100)[0..<4] // expected-error {{cannot convert call result type 'CountableRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} r0[0...4] // expected-error {{ambiguous use of 'subscript'}} r1[0...4] // expected-error {{ambiguous use of 'subscript'}} r2[0...4] // expected-error {{cannot convert call result type 'CountableClosedRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} r3[0...4] // expected-error {{cannot convert call result type 'CountableClosedRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} (10...100)[0...4] // expected-error {{cannot convert call result type 'CountableClosedRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} (UInt(10)...100)[0...4] // expected-error {{cannot convert call result type 'CountableClosedRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} r0[r0] // expected-error {{ambiguous use of 'subscript'}} r0[r1] // expected-error {{ambiguous reference to member 'subscript'}} r0[r2] // expected-error {{ambiguous use of 'subscript'}} r0[r3] // expected-error {{ambiguous reference to member 'subscript'}} r1[r0] // expected-error {{ambiguous reference to member 'subscript'}} r1[r1] // expected-error {{ambiguous use of 'subscript'}} r1[r2] // expected-error {{ambiguous reference to member 'subscript'}} r1[r3] // expected-error {{ambiguous use of 'subscript'}} r2[r0] // expected-error {{cannot convert value}} r2[r1] // expected-error {{cannot convert value}} r2[r2] // expected-error {{cannot convert value}} r2[r3] // expected-error {{cannot convert value}} r3[r0] // expected-error {{cannot convert value}} r3[r1] // expected-error {{cannot convert value}} r3[r2] // expected-error {{cannot convert value}} r3[r3] // expected-error {{cannot convert value}} } do { let r0: Range = 10..<100 let r1: Range = UInt(10)..<100 let r2: ClosedRange = 10...100 let r3: ClosedRange = UInt(10)...100 r0[0] // expected-error {{type 'Range<Int>' has no subscript members}} r1[0] // expected-error {{type 'Range<UInt>' has no subscript members}} r2[0] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r3[0] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} r0[UInt(0)] // expected-error {{type 'Range<Int>' has no subscript members}} r1[UInt(0)] // expected-error {{type 'Range<UInt>' has no subscript members}} r2[UInt(0)] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r3[UInt(0)] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} r0[0..<4] // expected-error {{type 'Range<Int>' has no subscript members}} r1[0..<4] // expected-error {{type 'Range<UInt>' has no subscript members}} r2[0..<4] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r3[0..<4] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} (10..<100)[0] // expected-error {{ambiguous use of 'subscript'}} (UInt(10)...100)[0..<4] // expected-error {{cannot convert call result type}} r0[0...4] // expected-error {{type 'Range<Int>' has no subscript members}} r1[0...4] // expected-error {{type 'Range<UInt>' has no subscript members}} r2[0...4] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r3[0...4] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} (10...100)[0...4] // expected-error {{cannot convert call result type 'CountableClosedRange<_>' to expected type 'Range<ClosedRangeIndex<_>>'}} (UInt(10)...100)[0...4] // expected-error {{cannot convert call result type}} r0[r0] // expected-error {{type 'Range<Int>' has no subscript members}} r0[r1] // expected-error {{type 'Range<Int>' has no subscript members}} r0[r2] // expected-error {{type 'Range<Int>' has no subscript members}} r0[r3] // expected-error {{type 'Range<Int>' has no subscript members}} r1[r0] // expected-error {{type 'Range<UInt>' has no subscript members}} r1[r1] // expected-error {{type 'Range<UInt>' has no subscript members}} r1[r2] // expected-error {{type 'Range<UInt>' has no subscript members}} r1[r3] // expected-error {{type 'Range<UInt>' has no subscript members}} r2[r0] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r2[r1] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r2[r2] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r2[r3] // expected-error {{type 'ClosedRange<Int>' has no subscript members}} r3[r0] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} r3[r1] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} r3[r2] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} r3[r3] // expected-error {{type 'ClosedRange<UInt>' has no subscript members}} } }
apache-2.0
5c5fdf283ccf2e81ab4e5609c74f1403
44.836237
171
0.624097
3.721358
false
false
false
false
katsana/katsana-sdk-ios
KatsanaSDK/Manager/KatsanaAPI+VehicleProfile.swift
1
4385
// // KatsanaAPI+VehicleProfile.swift // KatsanaSDK // // Created by Wan Ahmad Lutfi on 17/10/2016. // Copyright © 2016 pixelated. All rights reserved. // import Siesta extension KatsanaAPI { /// Save vehicle profile data /// /// public func saveVehicleProfile(vehicleId: String, data: [String: Any], completion: @escaping (_ vehicle: KTVehicle?) -> Void, failure: @escaping (_ error: RequestError?) -> Void = {_ in }) -> Void { let vehicle = vehicleWith(vehicleId: vehicleId) guard vehicle != nil else { return } let path = "vehicles/" + vehicleId let resource = self.API.resource(path) resource.request(.patch, json: data).onSuccess { entity in var insuranceExpiryChanged = false for (key, value) in data{ if let value = value as? String{ if key == "license_plate"{ vehicle?.vehicleNumber = value } else if key == "description"{ vehicle?.vehicleDescription = value } else if key == "manufacturer"{ vehicle?.manufacturer = value } else if key == "model"{ vehicle?.model = value } else if key == "insured_by"{ vehicle?.insuredBy = value } else if key == "insured_expiry"{ if vehicle?.insuredExpiryText != value{ insuranceExpiryChanged = true } vehicle?.insuredExpiryText = value } } } if let vehicle = vehicle, let idx = self.vehicles.index(of: vehicle){ self.vehicles[idx] = vehicle } if insuranceExpiryChanged{ NotificationCenter.default.post(name: KatsanaAPI.insuranceExpiryDateChangedNotification, object: vehicle) } completion(vehicle) }.onFailure { (error) in failure(error) self.log.error("Error save vehicle profile \(vehicleId), \(String(describing: error.errorDescription))") } } /// Save vehicle profile image. Function requestAllVehicles must be called first and the vehicle must be in the vehicle list /// /// - parameter vehicleId: vehicle id /// - parameter image: image to save /// - parameter completion: return vehicle public func saveVehicleProfileImage(vehicleId: String, image : KMImage?, completion: @escaping (_ vehicle: KTVehicle?) -> Void, failure: @escaping (_ error: Error?) -> Void = {_ in }) -> Void { let vehicle = vehicleWith(vehicleId: vehicleId) guard vehicle != nil else { return } var finalImage : KMImage! if image == nil { finalImage = KMImage(color: KMColor.white)! }else{ finalImage = image } finalImage = finalImage.fixOrientation() var maxSize : CGFloat = 600 #if os(iOS) let scale = UIScreen.main.scale #elseif os(OSX) let scale = (NSScreen.main()?.backingScaleFactor)! as CGFloat #endif if scale > 1 {maxSize /= scale} if ((finalImage.size.width) > maxSize || (finalImage.size.height) > maxSize) { let factor = finalImage.size.width/finalImage.size.height; if (factor > 1) { finalImage = finalImage.scale(to: CGSize(width: maxSize, height: maxSize / factor)) }else{ finalImage = finalImage.scale(to: CGSize(width: maxSize * factor, height: maxSize)) } } //Just put it although still not saved vehicle?.updateImage(finalImage) let path = self.baseURL().absoluteString + "vehicles/" + vehicleId + "/avatar" uploadImage(image: finalImage, path: path) { (success, error) in if success{ completion(vehicle) }else{ self.log.error("Error save vehicle profile image \(vehicleId), \(String(describing: error))") failure(error) } } } }
apache-2.0
9c27e3265de8345231fb603e9ddd1037
37.121739
202
0.528057
4.976163
false
false
false
false
4jchc/4jchc-BaiSiBuDeJie
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Tool/UIColor+Extension.swift
2
6865
// // UIColor+Extension.swift // 4j成才-微博 // // Created by 蒋进 on 15/12/1. // Copyright © 2015年 sijichcai. All rights reserved. // import UIKit ///*****✅随机颜色color extension UIColor { // class func randomColor() -> UIColor { // /* // 颜色有两种表现形式 RGB RGBA // RGB 24 // R,G,B每个颜色通道8位 // 8的二进制 255 // R,G,B每个颜色取值 0 ~255 // 120 / 255.0 // */ // let r:CGFloat = CGFloat(arc4random_uniform(UInt32(256))) / 255.0 // let g:CGFloat = CGFloat(arc4random_uniform(UInt32(256))) / 255.0 // let b:CGFloat = CGFloat(arc4random_uniform(UInt32(256))) / 255.0 // // return UIColor(red: r, green: g, blue: b, alpha: 1) // } //MARK: - 随机色 /// 随机色 static var randomColor:UIColor{ get{ return UIColor(red: randomNumber(), green: randomNumber(), blue: randomNumber() , alpha: 1.0) } } // class func randomColor() -> UIColor { // return UIColor(red: randomNumber(), green: randomNumber(), blue: randomNumber() , alpha: 1.0) // } class func randomNumber() -> CGFloat { // 0 ~ 255 return CGFloat(arc4random_uniform(256)) / CGFloat(255) } //UIColor(red: <#123#>/255.0, green: <#123#>/255.0, blue: <#123#>/255.0, alpha: 1.0) //MARK: - RGB色 /// RGB色 class func RGB(r:CGFloat,_ g:CGFloat, _ b:CGFloat, _ alpha:CGFloat = 1.0)->UIColor{ return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: alpha) } //MARK: 绿巨人 /// 绿巨人 static func greenMain() -> UIColor { return UIColor(red: (76/255.0), green: (217/255.0), blue: (100/255.0), alpha: 1.0) } static func redMain() -> UIColor { return UIColor(red: (255/255.0), green: (42/255.0), blue: (38/255.0), alpha: 1.0) } //MARK: Global整体的Tint /// Global整体的Tint func setupAsGlobalTint() { // global tint in File inspector seems to have a no effect UIView.appearance().tintColor = self } convenience init(hex: Int) { let red = CGFloat((hex & 0xff0000) >> 16) / 255.0 let green = CGFloat((hex & 0x00ff00) >> 8) / 255.0 let blue = CGFloat(hex & 0x0000ff) / 255.0 self.init(red: red, green: green, blue: blue, alpha: 1.0) } public convenience init(hex: String, alpha: CGFloat) { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString if (cString.hasPrefix("#")) { cString = cString.substringFromIndex(cString.startIndex.advancedBy(1)) } if (cString.characters.count != 6) { self.init(red: 0, green: 0, blue: 0, alpha: 0) } else { var rgbValue:UInt32 = 0 NSScanner(string: cString).scanHexInt(&rgbValue) self.init( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: alpha ) } } } public extension UIColor { public var lighterColor: UIColor { var r = CGFloat(0) var g = CGFloat(0) var b = CGFloat(0) var a = CGFloat(0) if getRed(&r, green: &g, blue: &b, alpha: &a) { return UIColor(red: min(r + 0.2, 1.0), green: min(g + 0.2, 1.0), blue: min(b + 0.2, 1.0), alpha: a) } else { assert(false, "Unable to get lighter color for color: \(self)") return self } } public var darkerColor: UIColor { var r = CGFloat(0) var g = CGFloat(0) var b = CGFloat(0) var a = CGFloat(0) if getRed(&r, green: &g, blue: &b, alpha: &a) { return UIColor(red: min(r - 0.2, 1.0), green: min(g - 0.2, 1.0), blue: min(b - 0.2, 1.0), alpha: a) } else { assert(false, "Unable to get lighter color for color: \(self)") return self } } } import Foundation extension UIColor { //MARK: - Lilac 紫丁香(淡紫色);adj.淡紫色的 /// Lilac 紫丁香(淡紫色);adj.淡紫色的 class func wishesLilac() -> UIColor { // light purple return UIColor(red: 186.0/255.0, green: 164.0/255.0, blue: 212.0/255.0, alpha: 1.0) } class func wishesPurple() -> UIColor { // dark purple return UIColor(red: 59.0/255.0, green: 32.0/255.0, blue: 89.0/255.0, alpha: 1.0) } class func wishesWhite() -> UIColor { // plain white return UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) } class func wishesGray() -> UIColor { // gray return UIColor(red: 117.0/255.0, green: 117.0/255.0, blue: 117.0/255.0, alpha: 1.0) } class func wishesGrayLight() -> UIColor { // gray return UIColor(red: 187.0/255.0, green: 187.0/255.0, blue: 187.0/255.0, alpha: 1.0) } class func wishesPink() -> UIColor { // pink return UIColor(red: 248.0/255.0, green: 106.0/255.0, blue: 162.0/255.0, alpha: 1.0) } class func wishesYellow() -> UIColor { // yellow return UIColor(red: 248.0/255.0, green: 184.0/255.0, blue: 1.0/255.0, alpha: 1.0) } } extension UIColor { func colorByChangingRed(redChange: CGFloat, greenChange: CGFloat, blueChange: CGFloat, alphaChange: CGFloat) -> UIColor { var rgba = [CGFloat](count: 4, repeatedValue: 0.0) getRed(&rgba[0], green: &rgba[1], blue: &rgba[2], alpha: &rgba[3]) rgba[0] = min(max(rgba[0] + redChange, 0.0), 1.0) rgba[1] = min(max(rgba[1] + greenChange, 0.0), 1.0) rgba[2] = min(max(rgba[2] + blueChange, 0.0), 1.0) rgba[3] = min(max(rgba[3] + alphaChange, 0.0), 1.0) return UIColor(red: rgba[0], green: rgba[1], blue: rgba[2], alpha: rgba[3]) } } extension UIColor { convenience init(hexString: String, alpha: CGFloat = 1) { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var hexValue: CUnsignedLongLong = 0 let scanner = NSScanner(string: hexString) scanner.scanLocation = 1 if scanner.scanHexLongLong(&hexValue) { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255 blue = CGFloat(hexValue & 0x0000FF) / 255 } self.init(red: red, green: green, blue: blue, alpha: alpha) } }
apache-2.0
d9dfdd0a9b07c157e598be70f23eb399
29.080717
149
0.536225
3.322437
false
false
false
false
antlr/antlr4
runtime/Swift/Sources/Antlr4/FailedPredicateException.swift
6
1750
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// A semantic predicate failed during validation. Validation of predicates /// occurs when normally parsing the alternative just like matching a token. /// Disambiguating predicate evaluation occurs when we test a predicate during /// prediction. /// public class FailedPredicateException: RecognitionException { private let ruleIndex: Int private let predicateIndex: Int private let predicate: String? public init(_ recognizer: Parser, _ predicate: String? = nil, _ message: String? = nil) { let s = recognizer.getInterpreter().atn.states[recognizer.getState()]! let trans = s.transition(0) as! AbstractPredicateTransition if let predex = trans as? PredicateTransition { self.ruleIndex = predex.ruleIndex self.predicateIndex = predex.predIndex } else { self.ruleIndex = 0 self.predicateIndex = 0 } self.predicate = predicate super.init(recognizer, recognizer.getInputStream()!, recognizer._ctx, FailedPredicateException.formatMessage(predicate, message)) if let token = try? recognizer.getCurrentToken() { setOffendingToken(token) } } public func getRuleIndex() -> Int { return ruleIndex } public func getPredIndex() -> Int { return predicateIndex } public func getPredicate() -> String? { return predicate } private static func formatMessage(_ predicate: String?, _ message: String?) -> String { if let message = message { return message } let predstr = predicate ?? "<unknown>" return "failed predicate: {\(predstr)}?" } }
bsd-3-clause
c2184568472364d9ab3cce4e17ab74af
27.688525
137
0.708
4.032258
false
false
false
false
mightydeveloper/swift
test/TypeCoercion/integer_literals.swift
10
1955
// RUN: %target-parse-verify-swift typealias IntegerLiteralType = Int32 // Simple coercion of literals. func simple() { _ = 1 as Int8 _ = 1 as Int16 } // Coercion of literals through operators. func operators(x1: Int8) { let x2 : Int8 = 1 + 2 let x3 : Int8 = 1 + x1 _ = x2 + 1 as Int8 _ = x1 + x2 + 1 + 4 + x3 + 5 as Int8 } // Check coercion failure due to overflow. struct X { } struct Y { } func accept_integer(x: Int8) -> X { } // expected-note 2{{found this candidate}} func accept_integer(x: Int16) -> Y { } // expected-note 2{{found this candidate}} func overflow_check() { var y : Y = accept_integer(500) accept_integer(17) // expected-error{{ambiguous use of 'accept_integer'}} accept_integer(1000000) // expected-error{{ambiguous use of 'accept_integer'}} } // Coercion chaining. struct meters : IntegerLiteralConvertible { var value : Int8 init(_ value: Int8) { self.value = value } typealias IntegerLiteralType = Int8 init(integerLiteral value: Int8) { self.value = value } } struct supermeters : IntegerLiteralConvertible { // expected-error{{type 'supermeters' does not conform to protocol 'IntegerLiteralConvertible'}} var value : meters typealias IntegerLiteralType = meters // expected-note{{possibly intended match 'IntegerLiteralType' (aka 'meters') does not conform to '_BuiltinIntegerLiteralConvertible'}} init(_integerLiteral value: meters) { self.value = value } } func chaining() { var length : meters = 17; // FIXME: missing truncation warning <rdar://problem/14070127>. var long_length : meters = 500; var really_long_length : supermeters = 10 } func memberaccess() { Int32(5._value) // expected-warning{{unused}} // This diagnostic is actually better than it looks, because the inner type is Builtin.Int32, not actually Int32. let x : Int32 = 7._value // expected-error{{cannot convert value of type 'Int32' to specified type 'Int32'}} _ = x }
apache-2.0
e193c4703cad85e2f5cb7c3096c3443d
27.75
175
0.686957
3.661049
false
false
false
false
lukevanin/OCRAI
CardScanner/GoogleVisionServiceAdapter.swift
1
2727
// // GoogleVisionServiceAdapter.swift // CardScanner // // Created by Luke Van In on 2017/02/19. // Copyright © 2017 Luke Van In. All rights reserved. // import Foundation import CoreData import GoogleVisionAPI struct GoogleVisionServiceAdapter: ImageAnnotationService { let service: GoogleVisionAPI func annotate(content: Document, completion: @escaping ImageAnnotationServiceCompletion) { DispatchQueue.main.async { [content, service] in guard let imageData = content.imageData else { completion(true, nil) return } let serviceRequest = GoogleVisionAPI.AnnotationImageRequest( image: GoogleVisionAPI.Image( data: imageData ), features: [ GoogleVisionAPI.Feature(type: .textDetection) ] ) service.annotate(requests: [serviceRequest]) { (responses, error) in guard let response = responses?.first else { completion(false, error) return } DispatchQueue.main.async { self.parseResponse(response: response, content: content) completion(true, nil) } } } } func parseResponse(response: GoogleVisionAPI.AnnotateImageResponse, content: Document) { guard let allEntities = response.textAnnotations, let rawText = allEntities.first?.description else { return } let allText = rawText.components(separatedBy: "\n").joined(separator: ", ") content.text = allText let entities = allEntities.dropFirst() var cursor = allText.startIndex ..< allText.endIndex entities.forEach { entity in guard let text = entity.description else { return } guard let range = allText.range(of: text, options: [], range: cursor), let vertices = entity.boundingPoly?.vertices else { fatalError("Invalid data") } let points = vertices.flatMap { (vertex) -> CGPoint? in guard let x = vertex.x, let y = vertex.y else { return nil } return CGPoint(x: x, y: y) } content.annotate( at: allText.convertRange(range), vertices: points ) cursor = range.upperBound ..< allText.endIndex } } }
mit
1d2bfa8b232000d4b863d6995f880399
30.333333
134
0.521277
5.66736
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Array/308_RangeSumQuery2DMutable.swift
1
3499
// // 308_RangeSumQuery2DMutable.swift // LeetcodeSwift // // Created by yansong li on 2016-11-27. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:308 Range Sum Query 2D - Mutable URL: https://leetcode.com/problems/range-sum-query-2d-mutable/ Space: O(N^2) Time: O(N^2) */ final class Range2DSumQueryMutable_Solution: Solution { var sumMatrix: [[Int]]? var keptMatrix: [[Int]]? func queryWithArray(_ array: [[Int]], startRow: Int, startCol: Int, endRow: Int, endCol: Int) -> Int { guard array.count > 0 && startRow < endRow && startCol < endCol && startRow >= 0 && endRow < array.count && startCol >= 0 && endCol < array[0].count else { return 0 } self.keptMatrix = array if self.sumMatrix == nil { self.constructSumMatrix(array: array) } let topRightSum = sumMatrix![startRow][endCol + 1] let bottomLeft = sumMatrix![endRow + 1][startCol] let commonPart = sumMatrix![startRow][startCol] let total = sumMatrix![endRow + 1][endCol + 1] return total - topRightSum - bottomLeft + commonPart } func queryWith(startRow: Int, startCol: Int, endRow: Int, endCol: Int) -> Int { let topRightSum = sumMatrix![startRow][endCol + 1] let bottomLeft = sumMatrix![endRow + 1][startCol] let commonPart = sumMatrix![startRow][startCol] let total = sumMatrix![endRow + 1][endCol + 1] return total - topRightSum - bottomLeft + commonPart } func constructSumMatrix(array: [[Int]]) { var computedSumMatrix = Array(repeating: Array(repeating: 0, count:array[0].count + 1), count: array.count + 1) for i in 1..<array.count + 1 { for j in 1..<array[0].count + 1 { let part1 = computedSumMatrix[i - 1][j] + computedSumMatrix[i][j - 1] let part2 = computedSumMatrix[i - 1][j - 1] + array[i - 1][j - 1] computedSumMatrix[i][j] = part1 - part2 } } self.sumMatrix = computedSumMatrix } func updateMatrixWith(value: Int, row: Int, col: Int) { guard var keptMatrix = self.keptMatrix, var sumMatrix = self.sumMatrix, (row >= 0 && row < keptMatrix.count && col >= 0 && col < keptMatrix[0].count) else { return } let changed = value - keptMatrix[row][col] for i in (row + 1)..<sumMatrix.count { for j in (col + 1)..<sumMatrix[0].count { sumMatrix[i][j] += changed } } keptMatrix[row][col] = value self.keptMatrix = keptMatrix self.sumMatrix = sumMatrix } override func test() { let result = self.queryWithArray([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]], startRow: 2, startCol: 1, endRow: 4, endCol: 3) print(result) self.updateMatrixWith(value: 2, row: 3, col: 2) let newResult = self.queryWith(startRow: 2, startCol: 1, endRow: 4, endCol: 3) print(newResult) } }
mit
5493341414bb89636a30c62645a0ded1
30.8
93
0.514008
3.765339
false
false
false
false
mliudev/hayaku
xcode/Food Tracker/Food Tracker/RatingControl.swift
1
2208
// // RatingControl.swift // Food Tracker // // Created by Manwe on 4/16/16. // Copyright © 2016 Manwe. All rights reserved. // import UIKit class RatingControl: UIView { // MARK: Properties var rating = 0 { didSet { setNeedsLayout() } } var ratingButtons = [UIButton]() let spacing = 5 let starCount = 5 // MARK: Initializer required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let emptyStarImage = UIImage(named: "emptyStar") let filledStarImage = UIImage(named: "filledStar") for _ in 0..<starCount { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) button.setImage(emptyStarImage, forState: .Normal) button.setImage(filledStarImage, forState: .Selected) button.setImage(filledStarImage, forState: [.Highlighted, .Selected]) button.adjustsImageWhenHighlighted = false button.addTarget( self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown) ratingButtons += [button] addSubview(button) } } override func layoutSubviews() { let buttonSize = Int(frame.size.height) var buttonFrame = CGRect(x:0, y:0, width: buttonSize, height: buttonSize) for (index, button) in ratingButtons.enumerate() { buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing)) button.frame = buttonFrame } updateButtonSelectionStates() } override func intrinsicContentSize() -> CGSize { let buttonSize = Int(frame.size.height) let width = (buttonSize * starCount) + (spacing * (starCount - 1)) return CGSize(width: width, height: buttonSize) } // MARK: Button Action func ratingButtonTapped(button: UIButton) { rating = ratingButtons.indexOf(button)! + 1 updateButtonSelectionStates() } func updateButtonSelectionStates() { for (index, button) in ratingButtons.enumerate() { button.selected = index < rating } } }
mit
8c211e804371a1c5861fe3e4d3110c7f
27.662338
83
0.602175
4.607516
false
false
false
false
M-Hamed/photo-editor
iOSPhotoEditor/PhotoEditor+Keyboard.swift
2
1821
// // PhotoEditor+Keyboard.swift // Pods // // Created by Mohamed Hamed on 6/16/17. // // import Foundation import UIKit extension PhotoEditorViewController { @objc func keyboardDidShow(notification: NSNotification) { if isTyping { doneButton.isHidden = false colorPickerView.isHidden = false hideToolbar(hide: true) } } @objc func keyboardWillHide(notification: NSNotification) { isTyping = false doneButton.isHidden = true hideToolbar(hide: false) } @objc func keyboardWillChangeFrame(_ notification: NSNotification) { if let userInfo = notification.userInfo { let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw) if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height { self.colorPickerViewBottomConstraint?.constant = 0.0 } else { self.colorPickerViewBottomConstraint?.constant = endFrame?.size.height ?? 0.0 } UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: { self.view.layoutIfNeeded() }, completion: nil) } } }
mit
ac82155c137505f74ab88c7626781d81
36.9375
131
0.634816
5.672897
false
false
false
false
orta/RxSwift
RxExample/RxExample/Services/ImageService.swift
1
2450
// // ImageService.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift import RxCocoa protocol ImageService { func imageFromURL(URL: NSURL) -> Observable<UIImage> } class DefaultImageService: ImageService { typealias Dependencies = ( URLSession: NSURLSession, imageDecodeScheduler: ImmediateScheduler, callbackScheduler: ImmediateScheduler ) var $: Dependencies // 1rst level cache let imageCache = NSCache() // 2nd level cache let imageDataCache = NSCache() init($: Dependencies) { self.$ = $ // cost is approx memory usage self.imageDataCache.totalCostLimit = 10 * MB self.imageCache.countLimit = 20 } func decodeImage(imageData: Observable<NSData>) -> Observable<UIImage> { return imageData >- observeSingleOn($.imageDecodeScheduler) >- mapOrDie { data in let maybeImage = UIImage(data: data) if maybeImage == nil { // some error return .Error(apiError("Decoding image error")) } let image = maybeImage! return success(image) } >- observeSingleOn($.callbackScheduler) } func imageFromURL(URL: NSURL) -> Observable<UIImage> { let maybeImage = self.imageDataCache.objectForKey(URL) as? UIImage let decodedImage: Observable<UIImage> // best case scenario, it's already decoded an in memory if let image = maybeImage { decodedImage = returnElement(image) } else { let cachedData = self.imageDataCache.objectForKey(URL) as? NSData // does image data cache contain anything if let cachedData = cachedData { decodedImage = returnElement(cachedData) >- decodeImage } else { // fetch from network decodedImage = $.URLSession.rx_data(NSURLRequest(URL: URL)) >- doOnNext { data in self.imageDataCache.setObject(data, forKey: URL) } >- decodeImage } } return decodedImage >- doOnNext { image in self.imageCache.setObject(image, forKey: URL) } } }
mit
e5c28eb9d2b06c73ff70da6b13a08c65
28.166667
97
0.574286
5.257511
false
false
false
false
jeroendesloovere/examples-swift
Swift-Playgrounds/SwiftBlog/2014-08-15-ValueAndReferenceTypes.playground/section-1.swift
2
805
// Value and Reference Types import Foundation // Value type example struct S { var data: Int = -1 } var a = S() var b = a // a is copied to b a.data = 42 // Changes a, not b println("\(a.data), \(b.data)") // Reference type example class C { var data: Int = -1 } var x = C() var y = x // x is copied to y x.data = 42 // changes the instance referred to by x (and y) println("\(x.data), \(y.data)") // Use a value type when: // - Comparing instance data with == makes sense // - You want copies to have independent state // - The data will be used in code across multiple threads // Use a reference type when: // - Comparing instance identity with === makes sense // - You want to create shared, mutable state
mit
82f58eb5370d2b64a043581818d79b1b
24.15625
80
0.586335
3.833333
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Extensions/UIImage+Utils.swift
1
4560
// // UIImage+Utils.swift // breadwallet // // Created by Adrian Corscadden on 2016-12-08. // Copyright © 2016-2019 Breadwinner AG. All rights reserved. // import UIKit import CoreGraphics private let inputImageKey = "inputImage" extension UIImage { static func qrCode(data: Data, color: CIColor = .black, backgroundColor: CIColor = .white) -> UIImage? { guard let qrFilter = CIFilter(name: "CIQRCodeGenerator"), let colorFilter = CIFilter(name: "CIFalseColor") else { return nil } qrFilter.setDefaults() qrFilter.setValue(data, forKey: "inputMessage") qrFilter.setValue("L", forKey: "inputCorrectionLevel") colorFilter.setDefaults() colorFilter.setValue(qrFilter.outputImage, forKey: "inputImage") colorFilter.setValue(color, forKey: "inputColor0") colorFilter.setValue(backgroundColor, forKey: "inputColor1") guard let outputImage = colorFilter.outputImage else { return nil } guard let cgImage = CIContext().createCGImage(outputImage, from: outputImage.extent) else { return nil } return UIImage(cgImage: cgImage) } func resize(_ size: CGSize, inset: CGFloat = 6.0) -> UIImage? { UIGraphicsBeginImageContext(size) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { assert(false, "Could not create image context"); return nil } guard let cgImage = self.cgImage else { assert(false, "No cgImage property"); return nil } context.interpolationQuality = .none context.rotate(by: π) // flip context.scaleBy(x: -1.0, y: 1.0) // mirror context.draw(cgImage, in: context.boundingBoxOfClipPath.insetBy(dx: inset, dy: inset)) return UIGraphicsGetImageFromCurrentImageContext() } static func imageForColor(_ color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image ?? UIImage() } func image(withInsets insets: UIEdgeInsets) -> UIImage? { let width = self.size.width + insets.left + insets.right let height = self.size.height + insets.top + insets.bottom UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, self.scale) let origin = CGPoint(x: insets.left, y: insets.top) self.draw(at: origin) let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageWithInsets?.withRenderingMode(renderingMode) } func tinted(with color: UIColor) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } color.set() withRenderingMode(.alwaysTemplate) .draw(in: CGRect(origin: .zero, size: size)) return UIGraphicsGetImageFromCurrentImageContext() } static func fetchAsync(from imageUrl: String, callback: @escaping (UIImage?) -> Void) { guard let url = URL(string: imageUrl) else { callback(nil) return } DispatchQueue.global(qos: .userInitiated).async { let data = try? Data(contentsOf: url) if let imageData = data, let image = UIImage(data: imageData) { DispatchQueue.main.async { callback(image) } } else { DispatchQueue.main.async { callback(nil) } } } } static func fetchAsync(from imageUrl: String, callback: @escaping (UIImage?, URL?) -> Void) { guard let url = URL(string: imageUrl) else { callback(nil, nil) return } DispatchQueue.global(qos: .userInitiated).async { let data = try? Data(contentsOf: url) if let imageData = data, let image = UIImage(data: imageData) { DispatchQueue.main.async { callback(image, url) } } else { DispatchQueue.main.async { callback(nil, nil) } } } } }
mit
27445e16f2e99c449b0a1821862c0c37
36.669421
126
0.607065
5.008791
false
false
false
false
hooman/swift
test/Distributed/Runtime/distributed_actor_isRemote.swift
1
3799
// RUN: %target-run-simple-swift(-Onone -Xfrontend -g -Xfrontend -enable-experimental-distributed -parse-as-library) | %FileCheck %s --dump-input=always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // REQUIRES: rdar78290608 import _Distributed @available(SwiftStdlib 5.5, *) distributed actor SomeSpecificDistributedActor { distributed func hello() async throws -> String { "local impl" } } @available(SwiftStdlib 5.5, *) extension SomeSpecificDistributedActor { @_dynamicReplacement(for: _remote_hello()) nonisolated func _remote_impl_hello() async throws -> String { return "remote impl (address: \(self.id))" } } // ==== Fake Transport --------------------------------------------------------- @available(SwiftStdlib 5.5, *) struct FakeActorID: ActorIdentity { let id: UInt64 } @available(SwiftStdlib 5.5, *) enum FakeTransportError: ActorTransportError { case unsupportedActorIdentity(AnyActorIdentity) } @available(SwiftStdlib 5.5, *) struct ActorAddress: ActorIdentity { let address: String init(parse address : String) { self.address = address } } @available(SwiftStdlib 5.5, *) struct FakeTransport: ActorTransport { func decodeIdentity(from decoder: Decoder) throws -> AnyActorIdentity { fatalError("not implemented:\(#function)") } func resolve<Act>(_ identity: AnyActorIdentity, as actorType: Act.Type) throws -> Act? where Act: DistributedActor { return nil } func assignIdentity<Act>(_ actorType: Act.Type) -> AnyActorIdentity where Act: DistributedActor { let id = ActorAddress(parse: "xxx") print("assignIdentity type:\(actorType), id:\(id)") return .init(id) } func actorReady<Act>(_ actor: Act) where Act: DistributedActor { print("actorReady actor:\(actor), id:\(actor.id)") } func resignIdentity(_ id: AnyActorIdentity) { print("resignIdentity id:\(id)") } } // ==== Execute ---------------------------------------------------------------- @_silgen_name("swift_distributed_actor_is_remote") func __isRemoteActor(_ actor: AnyObject) -> Bool func __isLocalActor(_ actor: AnyObject) -> Bool { return !__isRemoteActor(actor) } // ==== Execute ---------------------------------------------------------------- @available(SwiftStdlib 5.5, *) func test_remote() async { let address = ActorAddress(parse: "sact://127.0.0.1/example#1234") let transport = FakeTransport() let local = SomeSpecificDistributedActor(transport: transport) assert(__isLocalActor(local) == true, "should be local") assert(__isRemoteActor(local) == false, "should be local") print("isRemote(local) = \(__isRemoteActor(local))") // CHECK: isRemote(local) = false print("local.id = \(local.id)") // CHECK: local.id = AnyActorIdentity(ActorAddress(address: "xxx")) print("local.transport = \(local.actorTransport)") // CHECK: local.transport = FakeTransport() // assume it always makes a remote one let remote = try! SomeSpecificDistributedActor.resolve(.init(address), using: transport) assert(__isLocalActor(remote) == false, "should be remote") assert(__isRemoteActor(remote) == true, "should be remote") print("isRemote(remote) = \(__isRemoteActor(remote))") // CHECK: isRemote(remote) = true // Check the id and transport are the right values, and not trash memory print("remote.id = \(remote.id)") // CHECK: remote.id = AnyActorIdentity(ActorAddress(address: "sact://127.0.0.1/example#1234")) print("remote.transport = \(remote.actorTransport)") // CHECK: remote.transport = FakeTransport() print("done") // CHECK: done } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await test_remote() } }
apache-2.0
8eae0b795df6c55b36271d0aa9417afa
30.396694
152
0.666754
4.084946
false
false
false
false
alblue/swift-corelibs-foundation
Foundation/NSCFArray.swift
5
4719
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation internal final class _NSCFArray : NSMutableArray { deinit { _CFDeinit(self) _CFZeroUnsafeIvars(&_storage) } required init(coder: NSCoder) { fatalError() } required init(objects: UnsafePointer<AnyObject>?, count cnt: Int) { fatalError() } required public convenience init(arrayLiteral elements: Any...) { fatalError() } override var count: Int { return CFArrayGetCount(_cfObject) } override func object(at index: Int) -> Any { let value = CFArrayGetValueAtIndex(_cfObject, index) return _SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self)) } override func insert(_ value: Any, at index: Int) { let anObject = _SwiftValue.store(value) CFArrayInsertValueAtIndex(_cfMutableObject, index, unsafeBitCast(anObject, to: UnsafeRawPointer.self)) } override func removeObject(at index: Int) { CFArrayRemoveValueAtIndex(_cfMutableObject, index) } override var classForCoder: AnyClass { return NSMutableArray.self } } internal func _CFSwiftArrayGetCount(_ array: AnyObject) -> CFIndex { return (array as! NSArray).count } internal func _CFSwiftArrayGetValueAtIndex(_ array: AnyObject, _ index: CFIndex) -> Unmanaged<AnyObject> { let arr = array as! NSArray if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self { return Unmanaged.passUnretained(arr._storage[index]) } else { let value = _SwiftValue.store(arr.object(at: index)) let container: NSMutableDictionary if arr._storage.isEmpty { container = NSMutableDictionary() arr._storage.append(container) } else { container = arr._storage[0] as! NSMutableDictionary } container[NSNumber(value: index)] = value return Unmanaged.passUnretained(value) } } internal func _CFSwiftArrayGetValues(_ array: AnyObject, _ range: CFRange, _ values: UnsafeMutablePointer<Unmanaged<AnyObject>?>) { let arr = array as! NSArray if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self { for idx in 0..<range.length { values[idx] = Unmanaged.passUnretained(arr._storage[idx + range.location]) } } else { for idx in 0..<range.length { let index = idx + range.location let value = _SwiftValue.store(arr.object(at: index)) let container: NSMutableDictionary if arr._storage.isEmpty { container = NSMutableDictionary() arr._storage.append(container) } else { container = arr._storage[0] as! NSMutableDictionary } container[NSNumber(value: index)] = value values[idx] = Unmanaged.passUnretained(value) } } } internal func _CFSwiftArrayAppendValue(_ array: AnyObject, _ value: AnyObject) { (array as! NSMutableArray).add(value) } internal func _CFSwiftArraySetValueAtIndex(_ array: AnyObject, _ value: AnyObject, _ idx: CFIndex) { (array as! NSMutableArray).replaceObject(at: idx, with: value) } internal func _CFSwiftArrayReplaceValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) { (array as! NSMutableArray).replaceObject(at: idx, with: value) } internal func _CFSwiftArrayInsertValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) { (array as! NSMutableArray).insert(value, at: idx) } internal func _CFSwiftArrayExchangeValuesAtIndices(_ array: AnyObject, _ idx1: CFIndex, _ idx2: CFIndex) { (array as! NSMutableArray).exchangeObject(at: idx1, withObjectAt: idx2) } internal func _CFSwiftArrayRemoveValueAtIndex(_ array: AnyObject, _ idx: CFIndex) { (array as! NSMutableArray).removeObject(at: idx) } internal func _CFSwiftArrayRemoveAllValues(_ array: AnyObject) { (array as! NSMutableArray).removeAllObjects() } internal func _CFSwiftArrayReplaceValues(_ array: AnyObject, _ range: CFRange, _ newValues: UnsafeMutablePointer<Unmanaged<AnyObject>>, _ newCount: CFIndex) { NSUnimplemented() // (array as! NSMutableArray).replaceObjectsInRange(NSRange(location: range.location, length: range.length), withObjectsFrom: newValues.array(newCount)) }
apache-2.0
999c125edd595830235327dcd7685402
35.3
158
0.668786
4.49001
false
false
false
false
trafi/SlideOutable
Sources/SlideOutable/SlideOutable.swift
1
19011
// // SlideOutable.swift // SlideOutable // // Created by Domas Nutautas on 20/05/16. // Copyright © 2016 Domas Nutautas. All rights reserved. // import UIKit // MARK: - SlideOutable Implementation /// View that presents header and scroll in a sliding manner. open class SlideOutable: ClearContainerView { // MARK: Init /** Initializes and returns a newly allocated SlideOutable view object with specified scroll element. - Parameter frame: The `CGRect` to be passed for `UIView(frame:)` initializer. Defaults to `.zero`. - Parameter scroll: The `UIScrollView` that will be layed out in `SlideOutable` view's hierarchy. - Parameter header: The `UIView` to be added as a header above scroll - will be visible at all times. Make sure it's `bounds.height` is greater than 0 - it will be used as initial value for `minContentHeight`. Defaults to `nil`. - Returns: An initialized `SlideOutable` view object with `scroll` and optional `header` layed out in it's view hierarchy. */ public init(frame: CGRect = .zero, scroll: UIScrollView, header: UIView? = nil) { super.init(frame: frame) self.header = header self.scroll = scroll self.lastScrollOffset = scroll.contentOffset.y setupIfNeeded() } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func awakeFromNib() { super.awakeFromNib() setupIfNeeded() } private var needsSetup = true private func setupIfNeeded() { guard needsSetup else { return } needsSetup = false // Setup backgroundColor = .clear // Scroll scroll.removeFromSuperview() scroll.translatesAutoresizingMaskIntoConstraints = true scroll.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] scroll.frame = CGRect(x: 0, y: bounds.height - scroll.bounds.height, width: bounds.width, height: scroll.bounds.height) scroll.alwaysBounceVertical = true scroll.keyboardDismissMode = .onDrag addSubview(scroll) scroll.panGestureRecognizer.addTarget(self, action: #selector(SlideOutable.didPanScroll(_:))) scroll.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentSize), options: .new, context: &scrollContentContext) scroll.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), options: .new, context: &scrollContentContext) defer { updateScrollSize() update() } // Header guard let header = header else { return } assert(header.bounds.height >= 0, "`header` frame size height should be greater than 0") header.removeFromSuperview() header.translatesAutoresizingMaskIntoConstraints = true header.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] header.frame = CGRect(x: 0, y: scroll.frame.minY - header.bounds.height, width: bounds.width, height: header.bounds.height) minContentHeight = header.bounds.height addSubview(header) header.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(SlideOutable.didPanDrag(_:)))) } deinit { scroll?.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentSize), context: &scrollContentContext) scroll?.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), context: &scrollContentContext) subscrolls.allObjects.forEach { subscroll in subscroll.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), context: &scrollContentContext) } } // MARK: - Properties // MARK: Configurable /** The top padding that contents will not scroll on. Animatable. The default value is `0`. */ @IBInspectable open dynamic var topPadding: CGFloat = 0 { didSet { update() } } /** The mid anchor fraction from `0` (the very bottom) to `1` the very top of the `SlideOutable` view bounds. Setting it to `nil` would disable the anchoring. Animatable. The default value is `0.4`. */ open var anchorFraction: CGFloat? = 0.4 { didSet { update() } } /** The minimum content visible content (header and scroll) height. Animatable. The default value is header's `bounds.height` or `120` if header is not set. */ @IBInspectable open dynamic var minContentHeight: CGFloat = 120 { didSet { update() } } /** Proxy for `minimumContentHeight` without header's `bounds.height`. Animatable. */ @IBInspectable open var minScrollHeight: CGFloat { get { return minContentHeight - (header?.bounds.height ?? 0) } set { minContentHeight = newValue + (header?.bounds.height ?? 0) } } /** Determens weather the scroll's `bounds.height` can get bigger than it's `contentSize.height`. Animatable. The default value is `true`. */ @IBInspectable open var isScrollStretchable: Bool = true { didSet { update() } } /// The delegate of `SlideOutable` object. open weak var delegate: SlideOutableDelegate? open func addSubscroll(_ newScroll: UIScrollView) { newScroll.panGestureRecognizer.addTarget(self, action: #selector(SlideOutable.didPanScroll(_:))) newScroll.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), options: .new, context: &scrollContentContext) subscrolls.add(newScroll) } let subscrolls = NSHashTable<UIScrollView>.weakObjects() weak var lastActiveScroll: UIScrollView? { didSet { guard lastActiveScroll !== oldValue else { return } lastScrollOffset = activeScroll.contentOffset.y } } var activeScroll: UIScrollView { return lastActiveScroll ?? scroll } // MARK: Private // UI @IBOutlet open var header: UIView? @IBOutlet open var scroll: UIScrollView! // Offsets var lastScrollOffset: CGFloat = 0 var lastDragOffset: CGFloat = 0 // MARK: Computed /// Returns the current offest of `SlideOutable` object. public internal(set) var currentOffset: CGFloat { get { return (header ?? scroll).frame.minY } set { guard newValue != currentOffset else { return } // Save last state lastState = state(forOffset: newValue) // Change state header?.frame.origin.y = newValue scroll.frame.origin.y = header?.frame.maxY ?? newValue // Notifies `delegate` delegate?.slideOutable(self, stateChanged: stateForDelegate) } } /// Returns the current visible height of `SlideOutable` object. public var currentVisibleHeight: CGFloat { return bounds.height - currentOffset } var minOffset: CGFloat { if isScrollStretchable || subscrolls.count > 0 { return topPadding } else { let insets: UIEdgeInsets if #available(iOS 11.0, *) { insets = scroll.adjustedContentInset } else { insets = scroll.contentInset } let insetsOffset = insets.bottom + insets.top let calculatedOffset = bounds.height - (header?.bounds.height ?? 0) - scroll.contentSize.height - insetsOffset return max(topPadding, calculatedOffset) } } var maxOffset: CGFloat { return max(minOffset, bounds.height - minContentHeight) } var anchorOffset: CGFloat? { return anchorFraction.flatMap { bounds.height * (1 - $0) } } var snapOffsets: [CGFloat] { return [maxOffset, anchorOffset].reduce([minOffset]) { offsets, offset in guard let offset = offset, offset > minOffset else { return offsets } return offsets + [offset] } } // MARK: - Scroll content size KVO private var scrollContentContext = 0 open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &scrollContentContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } guard let keyPath = keyPath, let scroll = object as? UIScrollView else { return } guard subscrolls.count == 0 || self.scroll !== scroll else { return } switch keyPath { case #keyPath(UIScrollView.contentOffset): guard lastScrollOffset != scroll.contentOffset.y else { return } scrollViewDidScroll(scroll) case #keyPath(UIScrollView.contentSize): guard !isScrollStretchable && !isAnyGestureActive else { return } update() default: break } } // MARK: - State /// The state options of `SlideOutable` content. public enum State { public enum Settle { /// The contents are fully expanded. case expanded /// The contents are anchored to specified `anchorPoint`. case anchored /// The contents are fully collapsed. case collapsed } /// The contents are settled in one of the `Settle` cases. case settled(Settle) /// The contents are being interacted with. case dragging(offset: CGFloat) } /** Sets the `SlideOutable` view's state to specified `Settle` case. If there is no `anchorFraction` specified then `.anchored` will be ignored. Animatable. */ public func set(state: State.Settle) { lastState = .settled(state) guard let newOffset = offset(forState: state) else { return } currentOffset = newOffset } /// Returns the current state of `SlideOutable` view. public var state: State { return state(forOffset: currentOffset) } func state(forOffset offset: CGFloat) -> State { switch offset.equatable { case minOffset.equatable: return .settled(.expanded) case anchorOffset?.equatable ?? minOffset.equatable: // Makes compiler happy, dev sad :( return .settled(.anchored) case maxOffset.equatable: return .settled(.collapsed) default: return .dragging(offset: currentOffset) } } lazy var lastState: State = self.state func offset(forState state: State.Settle) -> CGFloat? { switch state { case .expanded: return minOffset case .anchored: return anchorOffset case .collapsed: return maxOffset } } var isAnyGestureActive: Bool { return activeScroll.panGestureRecognizer.isActive || header?.gestureRecognizers?.first { $0.isActive } != nil } var stateForDelegate: State { guard isAnyGestureActive else { return state } return .dragging(offset: currentOffset) } // MARK: - Interaction enum Interaction { case scroll case drag enum Direction { case up case down } init(direction: Direction, in state: State, scrolledToTop: Bool) { let scrollingToContentTop = !scrolledToTop && direction == .down if scrollingToContentTop { self = .scroll } else if case .settled(let settle) = state, settle == .expanded { switch direction { case .up: self = .scroll case .down: self = .drag } } else { self = .drag } } } func interaction(forDirection direction: Interaction.Direction) -> Interaction { return Interaction(direction: direction, in: state, scrolledToTop: activeScroll.contentOffset.y <= 0) } func interaction(scrollView: UIScrollView) -> Interaction { // Enable bouncing if case .settled = state, scrollView.isDecelerating { return .scroll } else { return interaction(forDirection: lastScrollOffset > scrollView.contentOffset.y ? .down : .up) } } func interaction(pan: UIPanGestureRecognizer) -> Interaction { return interaction(forDirection: pan.velocity(in: pan.view).y > 0 ? .down : .up) } // MARK: - Updates open override var frame: CGRect { didSet { guard oldValue.size != frame.size else { return } updateScrollSize() update() } } open override var bounds: CGRect { didSet { guard oldValue.size != bounds.size else { return } updateScrollSize() update() } } func updateScrollSize() { scroll?.frame.size = CGSize(width: bounds.width, height: bounds.height - (header?.bounds.height ?? 0) - topPadding) } func update(animated: Bool = false, to targetOffset: CGFloat? = nil, velocity: CGFloat? = nil, keepLastState: Bool = true) { guard scroll != nil else { return } // Get actual target let target: CGFloat if let targetOffset = targetOffset { target = targetOffset } else if keepLastState, case .settled(let settled) = lastState, let settledOffset = self.offset(forState: settled) { target = settledOffset } else { target = currentOffset } // Get actual offset let offset: CGFloat = snapOffsets.dropFirst().reduce(snapOffsets[0]) { closest, current in let closestDiff = abs(target - closest) let currentDiff = abs(target - current) return closestDiff < currentDiff ? closest : current } guard offset != currentOffset else { return } guard animated else { currentOffset = offset return } // Stop scroll decelerate activeScroll.stopDecelerating() let initialVelocity = CGVector(dx: (velocity ?? 0) / 1000 , dy: (velocity ?? 0) / 1000) let timingCurve = UISpringTimingParameters(dampingRatio: 0.8, initialVelocity: initialVelocity) let animator = UIViewPropertyAnimator(duration: 0.3, timingParameters: timingCurve) animator.addAnimations { self.currentOffset = offset } animator.addCompletion { (_) in self.updateScrollSize() } animator.startAnimation() } } // MARK: - Scrolling extension SlideOutable { fileprivate func scrollViewDidScroll(_ scrollView: UIScrollView) { guard scrollView.isDragging || scrollView.isDecelerating else { return } lastActiveScroll = scrollView switch interaction(scrollView: scrollView) { case .scroll: scrollView.showsVerticalScrollIndicator = true lastScrollOffset = scrollView.contentOffset.y case .drag: if lastScrollOffset > 0 && 0 > scrollView.contentOffset.y { // Accounts for missed content offset switching from .scroll to .drag lastDragOffset += lastScrollOffset lastScrollOffset = 0 } scrollView.showsVerticalScrollIndicator = false if lastScrollOffset >= 0 { scrollView.contentOffset.y = lastScrollOffset } } } } extension UIScrollView { func stopDecelerating() { setContentOffset(contentOffset, animated: false) } } extension SlideOutable { @objc func didPanScroll(_ pan: UIPanGestureRecognizer) { guard subscrolls.count == 0 || scroll !== pan.view else { return } lastActiveScroll = pan.view as? UIScrollView if pan.state == .began { header?.gestureRecognizers?.first?.stopCurrentGesture() } switch interaction(pan: pan) { case .scroll: lastDragOffset = pan.translation(in: pan.view).y guard pan.state == .ended, case .dragging = state else { break } didPanDrag(pan) case .drag: // Forwards interaction didPanDrag(pan) } } } // MARK: - Dragging extension SlideOutable { func offset(forDiff diff: CGFloat) -> (value: CGFloat, clipped: CGFloat)? { guard diff != 0 else { return nil } let targetOffset = currentOffset - diff let offset = min(maxOffset, max(minOffset, targetOffset)) return (offset, offset - targetOffset) } @objc public func didPanDrag(_ pan: UIPanGestureRecognizer) { let dragOffset = pan.translation(in: pan.view).y var diff = lastDragOffset - dragOffset let isScrollPan = activeScroll.panGestureRecognizer == pan switch pan.state { case .began where !isScrollPan: activeScroll.panGestureRecognizer.stopCurrentGesture() case .changed: // If starts dragging while scroll is in a bounce if lastScrollOffset < 0 { if isScrollPan { diff -= lastScrollOffset } lastScrollOffset = 0 activeScroll.contentOffset.y = 0 } guard let offset = offset(forDiff: diff) else { break } currentOffset = offset.value // Accounts for clipped pan switching from .drag to .scroll guard offset.clipped != 0, isScrollPan else { break } activeScroll.contentOffset.y += offset.clipped case .ended: let velocity = pan.velocity(in: pan.view).y let targetOffset = currentOffset - diff + 0.2 * velocity update(animated: true, to: targetOffset, velocity: velocity, keepLastState: false) default: break } lastDragOffset = dragOffset } } extension UIGestureRecognizer { func stopCurrentGesture() { isEnabled = !isEnabled isEnabled = !isEnabled } var isActive: Bool { return [.began, .changed].contains(state) } }
mit
b35de2f154b86dc3e6510d5194d6d1b1
32.350877
233
0.593793
5.08833
false
false
false
false
vbudhram/firefox-ios
StorageTests/TestSQLiteHistory.swift
2
71319
/* 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 @testable import Storage import Deferred import XCTest let threeMonthsInMillis: UInt64 = 3 * 30 * 24 * 60 * 60 * 1000 let threeMonthsInMicros: UInt64 = UInt64(threeMonthsInMillis) * UInt64(1000) // Start everything three months ago. let baseInstantInMillis = Date.now() - threeMonthsInMillis let baseInstantInMicros = Date.nowMicroseconds() - threeMonthsInMicros func advanceTimestamp(_ timestamp: Timestamp, by: Int) -> Timestamp { return timestamp + UInt64(by) } func advanceMicrosecondTimestamp(_ timestamp: MicrosecondTimestamp, by: Int) -> MicrosecondTimestamp { return timestamp + UInt64(by) } extension Site { func asPlace() -> Place { return Place(guid: self.guid!, url: self.url, title: self.title) } } class BaseHistoricalBrowserSchema: Schema { var name: String { return "BROWSER" } var version: Int { return -1 } func update(_ db: SQLiteDBConnection, from: Int) -> Bool { fatalError("Should never be called.") } func create(_ db: SQLiteDBConnection) -> Bool { return false } func drop(_ db: SQLiteDBConnection) -> Bool { return false } var supportsPartialIndices: Bool { let v = sqlite3_libversion_number() return v >= 3008000 // 3.8.0. } let oldFaviconsSQL = "CREATE TABLE IF NOT EXISTS favicons (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "width INTEGER, " + "height INTEGER, " + "type INTEGER NOT NULL, " + "date REAL NOT NULL" + ") " func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool { if let sql = sql { do { try db.executeChange(sql, withArgs: args) } catch { return false } } return true } func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool { for sql in queries { if let sql = sql { if !run(db, sql: sql) { return false } } } return true } func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql) { return false } } return true } } // Versions of BrowserSchema that we care about: // v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015. // This is when we first started caring about database versions. // // v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles. // // v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons. // // v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9. // // These tests snapshot the table creation code at each of these points. class BrowserSchemaV6: BaseHistoricalBrowserSchema { override var version: Int { return 6 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func CreateHistoryTable() -> String { return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func CreateDomainsTable() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func CreateQueueTable() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } override func create(_ db: SQLiteDBConnection) -> Bool { let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "\(TableFavicons).id AS iconID, " + "\(TableFavicons).url AS iconURL, " + "\(TableFavicons).date AS iconDate, " + "\(TableFavicons).type AS iconType, " + "MAX(\(TableFavicons).width) AS iconWidth " + "FROM \(TableFaviconSites), \(TableFavicons) WHERE " + "\(TableFaviconSites).faviconID = \(TableFavicons).id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT \(TableHistory).id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM \(TableHistory) " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).id = icons.siteID " let bookmarks = "CREATE TABLE IF NOT EXISTS bookmarks (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + "type TINYINT NOT NULL, " + "url TEXT, " + "parent INTEGER REFERENCES bookmarks(id) NOT NULL, " + "faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " + "title TEXT" + ") " let queries = [ // This used to be done by FaviconsTable. self.oldFaviconsSQL, CreateDomainsTable(), CreateHistoryTable(), visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, CreateQueueTable(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV7: BaseHistoricalBrowserSchema { override var version: Int { return 7 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS history (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func getDomainsTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func getQueueTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } override func create(_ db: SQLiteDBConnection) -> Bool { // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "favicons.id AS iconID, " + "favicons.url AS iconURL, " + "favicons.date AS iconDate, " + "favicons.type AS iconType, " + "MAX(favicons.width) AS iconWidth " + "FROM \(TableFaviconSites), favicons WHERE " + "\(TableFaviconSites).faviconID = favicons.id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT history.id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM history " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).id = icons.siteID " let bookmarks = "CREATE TABLE IF NOT EXISTS bookmarks (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + "type TINYINT NOT NULL, " + "url TEXT, " + "parent INTEGER REFERENCES bookmarks(id) NOT NULL, " + "faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " + "title TEXT" + ") " let queries = [ // This used to be done by FaviconsTable. self.oldFaviconsSQL, getDomainsTableCreationString(), getHistoryTableCreationString(), visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV8: BaseHistoricalBrowserSchema { override var version: Int { return 8 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func getDomainsTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func getQueueTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } override func create(_ db: SQLiteDBConnection) -> Bool { let favicons = "CREATE TABLE IF NOT EXISTS favicons (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "width INTEGER, " + "height INTEGER, " + "type INTEGER NOT NULL, " + "date REAL NOT NULL" + ") " // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS visits (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "favicons.id AS iconID, " + "favicons.url AS iconURL, " + "favicons.date AS iconDate, " + "favicons.type AS iconType, " + "MAX(favicons.width) AS iconWidth " + "FROM \(TableFaviconSites), favicons WHERE " + "\(TableFaviconSites).faviconID = favicons.id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT history.id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM history " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "history, \(ViewWidestFaviconsForSites) AS icons WHERE " + "history.id = icons.siteID " let bookmarks = "CREATE TABLE IF NOT EXISTS bookmarks (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + "type TINYINT NOT NULL, " + "url TEXT, " + "parent INTEGER REFERENCES bookmarks(id) NOT NULL, " + "faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " + "title TEXT" + ") " let queries: [String] = [ getDomainsTableCreationString(), getHistoryTableCreationString(), favicons, visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV10: BaseHistoricalBrowserSchema { override var version: Int { return 10 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString(forVersion version: Int = BrowserSchema.DefaultVersion) -> String { return "CREATE TABLE IF NOT EXISTS history (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func getDomainsTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func getQueueTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } func getBookmarksMirrorTableCreationString() -> String { // The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry. // For now we have the simplest possible schema: everything in one. let sql = "CREATE TABLE IF NOT EXISTS \(TableBookmarksMirror) " + // Shared fields. "( id INTEGER PRIMARY KEY AUTOINCREMENT" + ", guid TEXT NOT NULL UNIQUE" + ", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended. // Record/envelope metadata that'll allow us to do merges. ", server_modified INTEGER NOT NULL" + // Milliseconds. ", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean ", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted. ", parentid TEXT" + // GUID ", parentName TEXT" + // Type-specific fields. These should be NOT NULL in many cases, but we're going // for a sparse schema, so this'll do for now. Enforce these in the application code. ", feedUri TEXT, siteUri TEXT" + // LIVEMARKS ", pos INT" + // SEPARATORS ", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES ", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES ", folderName TEXT, queryId TEXT" + // QUERIES ", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" + ", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" + ")" return sql } /** * We need to explicitly store what's provided by the server, because we can't rely on * referenced child nodes to exist yet! */ func getBookmarksMirrorStructureTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " + "( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" + ", child TEXT NOT NULL" + // Should be the GUID of a child. ", idx INTEGER NOT NULL" + // Should advance from 0. ")" } override func create(_ db: SQLiteDBConnection) -> Bool { let favicons = "CREATE TABLE IF NOT EXISTS favicons (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "width INTEGER, " + "height INTEGER, " + "type INTEGER NOT NULL, " + "date REAL NOT NULL" + ") " // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS visits (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON visits (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "favicons.id AS iconID, " + "favicons.url AS iconURL, " + "favicons.date AS iconDate, " + "favicons.type AS iconType, " + "MAX(favicons.width) AS iconWidth " + "FROM \(TableFaviconSites), favicons WHERE " + "\(TableFaviconSites).faviconID = favicons.id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT history.id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM history " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "history, \(ViewWidestFaviconsForSites) AS icons WHERE " + "history.id = icons.siteID " let bookmarks = "CREATE TABLE IF NOT EXISTS bookmarks (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + "type TINYINT NOT NULL, " + "url TEXT, " + "parent INTEGER REFERENCES bookmarks(id) NOT NULL, " + "faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " + "title TEXT" + ") " let bookmarksMirror = getBookmarksMirrorTableCreationString() let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString() let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let queries: [String] = [ getDomainsTableCreationString(), getHistoryTableCreationString(), favicons, visits, bookmarks, bookmarksMirror, bookmarksMirrorStructure, indexStructureParentIdx, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class TestSQLiteHistory: XCTestCase { let files = MockFiles() fileprivate func deleteDatabases() { for v in ["6", "7", "8", "10", "6-data"] { do { try files.remove("browser-v\(v).db") } catch {} } do { try files.remove("browser.db") try files.remove("historysynced.db") } catch {} } override func tearDown() { super.tearDown() self.deleteDatabases() } override func setUp() { super.setUp() // Just in case tearDown didn't run or succeed last time! self.deleteDatabases() } // Test that our visit partitioning for frecency is correct. func testHistoryLocalAndRemoteVisits() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let siteL = Site(url: "http://url1/", title: "title local only") let siteR = Site(url: "http://url2/", title: "title remote only") let siteB = Site(url: "http://url3/", title: "title local and remote") siteL.guid = "locallocal12" siteR.guid = "remoteremote" siteB.guid = "bothbothboth" let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link) let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link) let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link) let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link) let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link) let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link) let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link) let deferred = history.clearHistory() >>> { history.addLocalVisit(siteVisitL1) } >>> { history.addLocalVisit(siteVisitL2) } >>> { history.addLocalVisit(siteVisitBL1) } >>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) } >>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) } >>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) } // Do this step twice, so we exercise the dupe-visit handling. >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) } >>> { history.getFrecentHistory().getSites(whereURLContains: nil, historyLimit: 3, bookmarksLimit: 0) >>== { (sites: Cursor) -> Success in XCTAssertEqual(3, sites.count) // Two local visits beat a single later remote visit and one later local visit. // Two local visits beat three remote visits. XCTAssertEqual(siteL.guid!, sites[0]!.guid!) XCTAssertEqual(siteB.guid!, sites[1]!.guid!) XCTAssertEqual(siteR.guid!, sites[2]!.guid!) return succeed() } // This marks everything as modified so we can fetch it. >>> history.onRemovedAccount // Now check that we have no duplicate visits. >>> { history.getModifiedHistoryToUpload() >>== { (places) -> Success in if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) { XCTAssertEqual(3, visits.count) } else { XCTFail("Couldn't find site R.") } return succeed() } } } XCTAssertTrue(deferred.value.isSuccess) } func testUpgrades() { let sources: [(Int, Schema)] = [ (6, BrowserSchemaV6()), (7, BrowserSchemaV7()), (8, BrowserSchemaV8()), (10, BrowserSchemaV10()), ] let destination = BrowserSchema() for (version, schema) in sources { var db = BrowserDB(filename: "browser-v\(version).db", schema: schema, files: files) XCTAssertTrue(db.withConnection({ connection -> Int in connection.version }).value.successValue == schema.version, "Creating BrowserSchema at version \(version)") db.forceClose() db = BrowserDB(filename: "browser-v\(version).db", schema: destination, files: files) XCTAssertTrue(db.withConnection({ connection -> Int in connection.version }).value.successValue == destination.version, "Upgrading BrowserSchema from version \(version) to version \(schema.version)") db.forceClose() } } func testUpgradesWithData() { var db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchemaV6(), files: files) // Insert some data. let queries = [ "INSERT INTO domains (id, domain) VALUES (1, 'example.com')", "INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)", "INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)", "INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)", "INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)", "INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')" ] XCTAssertTrue(db.run(queries).value.isSuccess) // And we can upgrade to the current version. db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let results = history.getSitesByLastVisit(10).value.successValue XCTAssertNotNil(results) XCTAssertEqual(results![0]?.url, "http://www.example.com") db.forceClose() } func testDomainUpgrade() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let site = Site(url: "http://www.example.com/test1.1", title: "title one") // Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden. let insertDeferred = db.withConnection { connection -> Void in try connection.executeChange("PRAGMA foreign_keys = OFF") let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) VALUES (?, ?, ?, ?, ?, ?, ?)" let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1] try connection.executeChange(insert, withArgs: args) } XCTAssertTrue(insertDeferred.value.isSuccess) // Now insert it again. This should update the domain. history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link)).succeeded() // domain_id isn't normally exposed, so we manually query to get it. let resultsDeferred = db.withConnection { connection -> Cursor<Int?> in let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?" let args: Args = [site.url] return connection.executeQuery(sql, factory: { $0[0] as? Int }, withArgs: args) } let results = resultsDeferred.value.successValue! let domain = results[0]! // Unwrap to get the first item from the cursor. XCTAssertNil(domain) } func testDomains() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let initialGuid = Bytes.generateGUID() let site11 = Site(url: "http://www.example.com/test1.1", title: "title one") let site12 = Site(url: "http://www.example.com/test1.2", title: "title two") let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three") let site3 = Site(url: "http://www.example2.com/test1", title: "title three") let expectation = self.expectation(description: "First.") let clearTopSites = "DELETE FROM \(TableCachedTopSites)" let updateTopSites: [(String, Args?)] = [(clearTopSites, nil), (history.getFrecentHistory().updateTopSitesCacheQuery())] func countTopSites() -> Deferred<Maybe<Cursor<Int>>> { return db.runQuery("SELECT COUNT(*) from \(TableCachedTopSites)", args: nil, factory: { sdrow -> Int in return sdrow[0] as? Int ?? 0 }) } history.clearHistory().bind({ success in return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))]) }).bind({ (results: [Maybe<()>]) in return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds()) }).bind({ guid -> Success in XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct") return db.run(updateTopSites) }).bind({ success in XCTAssertTrue(success.isSuccess, "update was successful") return countTopSites() }).bind({ (count: Maybe<Cursor<Int>>) -> Success in XCTAssert(count.successValue![0] == 2, "2 sites returned") return history.removeSiteFromTopSites(site11) }).bind({ success -> Success in XCTAssertTrue(success.isSuccess, "Remove was successful") return db.run(updateTopSites) }).bind({ success -> Deferred<Maybe<Cursor<Int>>> in XCTAssertTrue(success.isSuccess, "update was successful") return countTopSites() }) .upon({ (count: Maybe<Cursor<Int>>) in XCTAssert(count.successValue![0] == 1, "1 site returned") expectation.fulfill() }) waitForExpectations(timeout: 10.0) { error in return } } func testHistoryIsSynced() { let db = BrowserDB(filename: "historysynced.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let initialGUID = Bytes.generateGUID() let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title") XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true) XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess) XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false) } // This is a very basic test. Adds an entry, retrieves it, updates it, // and then clears the database. func testHistoryTable() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let bookmarks = SQLiteBookmarks(db: db) let site1 = Site(url: "http://url1/", title: "title one") let site1Changed = Site(url: "http://url1/", title: "title one alt") let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link) let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark) let site2 = Site(url: "http://url2/", title: "title two") let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getFrecentHistory().getSites(whereURLContains: nil, historyLimit: 10, bookmarksLimit: 0) >>== f } } func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getSitesByLastVisit(10) >>== f } } func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getFrecentHistory().getSites(whereURLContains: filter, historyLimit: 10, bookmarksLimit: 0) >>== f } } func checkDeletedCount(_ expected: Int) -> () -> Success { return { history.getDeletedHistoryToUpload() >>== { guids in XCTAssertEqual(expected, guids.count) return succeed() } } } history.clearHistory() >>> { history.addLocalVisit(siteVisit1) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1.title, sites[0]!.title) XCTAssertEqual(site1.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit2) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site1Changed.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit3) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(2, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site2.title, sites[1]!.title) return succeed() } >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(2, sites.count) // They're in order of date last visited. let first = sites[0]! let second = sites[1]! XCTAssertEqual(site2.title, first.title) XCTAssertEqual(site1Changed.title, second.title) XCTAssertTrue(siteVisit3.date == first.latestVisit!.date) return succeed() } >>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in XCTAssertEqual(1, sites.count) let first = sites[0]! XCTAssertEqual(site2.title, first.title) return succeed() } >>> checkDeletedCount(0) >>> { history.removeHistoryForURL("http://url2/") } >>> checkDeletedCount(1) >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) return succeed() } >>> { history.clearHistory() } >>> checkDeletedCount(0) >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> done waitForExpectations(timeout: 10.0) { error in return } } func testFaviconTable() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let bookmarks = SQLiteBookmarks(db: db) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func updateFavicon() -> Success { let fav = Favicon(url: "http://url2/", date: Date()) fav.id = 1 let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark") return history.addFavicon(fav, forSite: site) >>> succeed } func checkFaviconForBookmarkIsNil() -> Success { return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in XCTAssertEqual(1, results.count) XCTAssertNil(results[0]?.favicon) return succeed() } } func checkFaviconWasSetForBookmark() -> Success { return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in XCTAssertEqual(1, results.count) if let actualFaviconURL = results[0]??.url { XCTAssertEqual("http://url2/", actualFaviconURL) } return succeed() } } func removeBookmark() -> Success { return bookmarks.testFactory.removeByURL("http://bookmarkedurl/") } func checkFaviconWasRemovedForBookmark() -> Success { return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in XCTAssertEqual(0, results.count) return succeed() } } history.clearAllFavicons() >>> bookmarks.clearBookmarks >>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) } >>> checkFaviconForBookmarkIsNil >>> updateFavicon >>> checkFaviconWasSetForBookmark >>> removeBookmark >>> checkFaviconWasRemovedForBookmark >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesFrecencyOrder() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 100) // Create a new site thats for an existing domain but a different URL. let site = Site(url: "http://s\(5)ite\(5).com/foo-different-url", title: "A \(5) different url") site.guid = "abc\(5)defhi" history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded() // Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite! for i in 0...100 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)defhi") return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesFiltersGoogle() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 100) func createTopSite(url: String, guid: String) { let site = Site(url: url, title: "Hi") site.guid = guid history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded() // Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite! for i in 0...100 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } } createTopSite(url: "http://google.com", guid: "abcgoogle") // should not be a topsite createTopSite(url: "http://www.google.com", guid: "abcgoogle1") // should not be a topsite createTopSite(url: "http://google.co.za", guid: "abcgoogleza") // should not be a topsite createTopSite(url: "http://docs.google.com", guid: "docsgoogle") // should be a topsite let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites[0]?.guid, "docsgoogle") // google docs should be the first topsite // make sure all other google guids are not in the topsites array topSites.forEach { let guid: String = $0!.guid! // type checking is hard XCTAssertNil(["abcgoogle", "abcgoogle1", "abcgoogleza"].index(of: guid)) } XCTAssertEqual(topSites.count, 20) return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesCache() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Make sure that we get back the top sites populateHistoryForFrecencyCalculations(history, siteCount: 100) // Add extra visits to the 5th site to bubble it to the top of the top sites cache let site = Site(url: "http://s\(5)ite\(5).com/foo", title: "A \(5)") site.guid = "abc\(5)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } func invalidateIfNeededDoesntChangeResults() -> Success { return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } } func addVisitsToZerothSite() -> Success { let site = Site(url: "http://s\(0)ite\(0).com/foo", title: "A \(0)") site.guid = "abc\(0)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } return succeed() } func markInvalidation() -> Success { history.setTopSitesNeedsInvalidation() return succeed() } func checkSitesInvalidate() -> Success { history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded() return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") XCTAssertEqual(topSites[1]!.guid, "abc\(0)def") return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> invalidateIfNeededDoesntChangeResults >>> markInvalidation >>> addVisitsToZerothSite >>> checkSitesInvalidate >>> done waitForExpectations(timeout: 10.0) { error in return } } func testPinnedTopSites() { let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // add 2 sites to pinned topsite // get pinned site and make sure it exists in the right order // remove pinned sites // make sure pinned sites dont exist // create pinned sites. let site1 = Site(url: "http://s\(1)ite\(1).com/foo", title: "A \(1)") site1.id = 1 site1.guid = "abc\(1)def" addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now()) let site2 = Site(url: "http://s\(2)ite\(2).com/foo", title: "A \(2)") site2.id = 2 site2.guid = "abc\(2)def" addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now()) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func addPinnedSites() -> Success { return history.addPinnedTopSite(site1) >>== { sleep(1) // Sleep to prevent intermittent issue with sorting on the timestamp return history.addPinnedTopSite(site2) } } func checkPinnedSites() -> Success { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 2) XCTAssertEqual(pinnedSites[0]!.url, site2.url) XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last") return succeed() } } func removePinnedSites() -> Success { return history.removeFromPinnedTopSites(site2) >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site") XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left") return succeed() } } } func dupePinnedSite() -> Success { return history.addPinnedTopSite(site1) >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "There should not be a dupe") XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left") return succeed() } } } func removeHistory() -> Success { return history.clearHistory() >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "Pinned sites should exist after a history clear") return succeed() } } } addPinnedSites() >>> checkPinnedSites >>> removePinnedSites >>> dupePinnedSite >>> removeHistory >>> done waitForExpectations(timeout: 10.0) { error in return } } } class TestSQLiteHistoryTransactionUpdate: XCTestCase { func testUpdateInTransaction() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.clearHistory().succeeded() let site = Site(url: "http://site/foo", title: "AA") site.guid = "abcdefghiabc" history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded() let ts: MicrosecondTimestamp = baseInstantInMicros let local = SiteVisit(site: site, date: ts, type: VisitType.link) XCTAssertTrue(history.addLocalVisit(local).value.isSuccess) } } class TestSQLiteHistoryFilterSplitting: XCTestCase { let history: SQLiteHistory = { let files = MockFiles() let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() return SQLiteHistory(db: db, prefs: prefs) }() func testWithSingleWord() { let (fragment, args) = computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foo"])) } func testWithIdenticalWords() { let (fragment, args) = computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foo"])) } func testWithDistinctWords() { let (fragment, args) = computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "? AND ?") XCTAssert(stringArgsEqual(args, ["foo", "bar"])) } func testWithDistinctWordsAndWhitespace() { let (fragment, args) = computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "? AND ?") XCTAssert(stringArgsEqual(args, ["foo", "bar"])) } func testWithSubstrings() { let (fragment, args) = computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foobar"])) } func testWithSubstringsAndIdenticalWords() { let (fragment, args) = computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foobar"])) } fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool { return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in return (oneElement as! String) == (otherElement as! String) }) } } // MARK - Private Test Helper Methods enum VisitOrigin { case local case remote } private func populateHistoryForFrecencyCalculations(_ history: SQLiteHistory, siteCount count: Int) { for i in 0...count { let site = Site(url: "http://s\(i)ite\(i).com/foo", title: "A \(i)") site.guid = "abc\(i)def" let baseMillis: UInt64 = baseInstantInMillis - 20000 history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).succeeded() for j in 0...20 { let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j)) addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime) addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime - 100) } } } func addVisitForSite(_ site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: MicrosecondTimestamp) { let visit = SiteVisit(site: site, date: atTime, type: VisitType.link) switch from { case .local: history.addLocalVisit(visit).succeeded() case .remote: history.storeRemoteVisits([visit], forGUID: site.guid!).succeeded() } }
mpl-2.0
c91b1e3e41d2b44345d8eb64619a6172
42.888615
231
0.588777
4.875846
false
false
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/Publishers+URLSession.swift
1
6477
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Only support 64bit #if !(os(iOS) && (arch(i386) || arch(arm))) @_exported import Foundation // Clang module import Combine // MARK: Data Tasks @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension URLSession { /// Returns a publisher that wraps a URL session data task for a given URL. /// /// The publisher publishes data when the task completes, or terminates if the task fails with an error. /// - Parameter url: The URL for which to create a data task. /// - Returns: A publisher that wraps a data task for the URL. public func dataTaskPublisher( for url: URL) -> DataTaskPublisher { let request = URLRequest(url: url) return DataTaskPublisher(request: request, session: self) } /// Returns a publisher that wraps a URL session data task for a given URL request. /// /// The publisher publishes data when the task completes, or terminates if the task fails with an error. /// - Parameter request: The URL request for which to create a data task. /// - Returns: A publisher that wraps a data task for the URL request. public func dataTaskPublisher( for request: URLRequest) -> DataTaskPublisher { return DataTaskPublisher(request: request, session: self) } public struct DataTaskPublisher: Publisher { public typealias Output = (data: Data, response: URLResponse) public typealias Failure = URLError public let request: URLRequest public let session: URLSession public init(request: URLRequest, session: URLSession) { self.request = request self.session = session } public func receive<S: Subscriber>(subscriber: S) where Failure == S.Failure, Output == S.Input { subscriber.receive(subscription: Inner(self, subscriber)) } private typealias Parent = DataTaskPublisher private final class Inner<Downstream: Subscriber>: Subscription, CustomStringConvertible, CustomReflectable, CustomPlaygroundDisplayConvertible where Downstream.Input == Parent.Output, Downstream.Failure == Parent.Failure { typealias Input = Downstream.Input typealias Failure = Downstream.Failure private let lock: Lock private var parent: Parent? // GuardedBy(lock) private var downstream: Downstream? // GuardedBy(lock) private var demand: Subscribers.Demand // GuardedBy(lock) private var task: URLSessionDataTask! // GuardedBy(lock) var description: String { return "DataTaskPublisher" } var customMirror: Mirror { lock.lock() defer { lock.unlock() } return Mirror(self, children: [ "task": task as Any, "downstream": downstream as Any, "parent": parent as Any, "demand": demand, ]) } var playgroundDescription: Any { return description } init(_ parent: Parent, _ downstream: Downstream) { self.lock = Lock() self.parent = parent self.downstream = downstream self.demand = .max(0) } deinit { lock.cleanupLock() } // MARK: - Upward Signals func request(_ d: Subscribers.Demand) { precondition(d > 0, "Invalid request of zero demand") lock.lock() guard let p = parent else { // We've already been cancelled so bail lock.unlock() return } // Avoid issues around `self` before init by setting up only once here if self.task == nil { let task = p.session.dataTask( with: p.request, completionHandler: handleResponse(data:response:error:) ) self.task = task } self.demand += d let task = self.task! lock.unlock() task.resume() } private func handleResponse(data: Data?, response: URLResponse?, error: Error?) { lock.lock() guard demand > 0, parent != nil, let ds = downstream else { lock.unlock() return } parent = nil downstream = nil // We clear demand since this is a single shot shape demand = .max(0) task = nil lock.unlock() if let response = response, error == nil { _ = ds.receive((data ?? Data(), response)) ds.receive(completion: .finished) } else { let urlError = error as? URLError ?? URLError(.unknown) ds.receive(completion: .failure(urlError)) } } func cancel() { lock.lock() guard parent != nil else { lock.unlock() return } parent = nil downstream = nil demand = .max(0) let task = self.task self.task = nil lock.unlock() task?.cancel() } } } } #endif /* !(os(iOS) && (arch(i386) || arch(arm))) */
apache-2.0
97599f3f3ef0623e55c28a91901103e9
36.011429
151
0.498224
5.545377
false
false
false
false
riehs/on-the-map
On the Map/On the Map/AddPinViewController.swift
1
5272
// // AddPinViewController.swift // On the Map // // Created by Daniel Riehs on 3/22/15. // Copyright (c) 2015 Daniel Riehs. All rights reserved. // import UIKit import MapKit class AddPinViewController: UIViewController, MKMapViewDelegate, UITextFieldDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var findButton: UIButton! @IBOutlet weak var addressField: UITextField! @IBOutlet weak var linkField: UITextField! @IBOutlet weak var submitButton: UIButton! @IBOutlet weak var workingMessage: UILabel! let LINK_FIELD = 1 var coordinates: CLLocationCoordinate2D! @IBAction func tapCancelButton(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } @IBAction func tapFindButton(_ sender: AnyObject) { findOnMap() } override func viewDidLoad() { super.viewDidLoad() linkField.tag = LINK_FIELD //This is required to add "http://" to the linkField text field when a user starts typing, and to call a findOnMap() when the return key is pressed. linkField.delegate = self //This is required to call the findOnMap() function when the return key is pressed. addressField.delegate = self //These items aren't revealed until the user successfully finds a location. mapView.isHidden = true submitButton.isHidden = true workingMessage.isHidden = true } //Calls the findOnMap() function when the keyboard return key is pressed. func textFieldShouldReturn(_ textField: UITextField) -> Bool { findOnMap() return true } func findOnMap() { //Indicates the geocoding is in process. workingMessage.isHidden = false let location = addressField.text let geocoder: CLGeocoder = CLGeocoder() //Geocodes the location. geocoder.geocodeAddressString(location!, completionHandler: { (placemarks, error) -> Void in //Returns an error if geocoding is unsuccessful. if ((error) != nil) { self.workingMessage.isHidden = true self.errorAlert("Invalid location", error: "Please try again.") } //If geocoding is successful, multiple locations may be returned in an array. Only the first location is used below. else if placemarks?[0] != nil { let placemark: CLPlacemark = placemarks![0] //Creats a coordinate and annotation. let coordinates: CLLocationCoordinate2D = placemark.location!.coordinate let pointAnnotation: MKPointAnnotation = MKPointAnnotation() pointAnnotation.coordinate = coordinates //Displays the map. self.mapView.isHidden = false //Places the annotation on the map. self.mapView?.addAnnotation(pointAnnotation) //Centers the map on the coordinates. self.mapView?.centerCoordinate = coordinates //Sets the zoom level on the map. self.mapView?.camera.altitude = 3000000; //Sets the coordinates parameter that is used if the user decides to submit this location. self.coordinates = coordinates //Items used to look for a location are hidden. self.workingMessage.isHidden = true self.findButton.isHidden = true self.addressField.isHidden = true //The keyboad is dismissed. self.addressField.resignFirstResponder() //This is necessary because the user may have moved his cursor to the linkField text field. self.linkField.resignFirstResponder() //The user can now submit the location. self.submitButton.isHidden = false } }) } @IBAction func submitLocation(_ sender: AnyObject) { if validateUrl(linkField.text!) == false { errorAlert("Invalid URL", error: "Please try again.") } else { //Prevents user from submitting twice. submitButton.isHidden = true //Indicates that the app is working workingMessage.isHidden = false //Submits the new data point. MapPoints.sharedInstance().submitData(coordinates.latitude.description, longitude: coordinates.longitude.description, addressField: addressField.text!, link: linkField.text!) { (success, errorString) in if success { DispatchQueue.main.async(execute: { MapPoints.sharedInstance().needToRefreshData = true self.dismiss(animated: true, completion: nil) }) } else { DispatchQueue.main.async(execute: { //If there is an error, the submit button is unhidden so that the user can try again. self.submitButton.isHidden = false self.workingMessage.isHidden = true self.errorAlert("Error", error: errorString!) }) } } } } //Creates an Alert-style error message. func errorAlert(_ title: String, error: String) { let controller: UIAlertController = UIAlertController(title: title, message: error, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(controller, animated: true, completion: nil) } //Makes it easier for the user to enter a valid link. func textFieldDidBeginEditing(_ textField: UITextField) { if textField.tag == LINK_FIELD { textField.text = "http://" } } //Regular expression used for validating submitted URLs. func validateUrl(_ url: String) -> Bool { let pattern = "^(https?:\\/\\/)([a-zA-Z0-9_\\-~]+\\.)+[a-zA-Z0-9_\\-~\\/\\.]+$" if url.range(of: pattern, options: .regularExpression) != nil { return true } return false } }
mit
d1b0a3ac903316af312b0b0768594ed2
28.127072
205
0.710357
4.071042
false
false
false
false
XWJACK/Music
Music/Modules/Player/MusicPlayerCoverView.swift
1
2263
// // MusicPlayerCoverView.swift // Music // // Created by Jack on 5/15/17. // Copyright © 2017 Jack. All rights reserved. // import UIKit class MusicPlayerCoverView: UIView { // private let discBackgroundImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "player_disc_background")) // private let coverImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "player_cover")) private let albumImageView: UIImageView = UIImageView() private let discImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "player_disc")) private let maskImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "player_mask")) override init(frame: CGRect) { super.init(frame: frame) // addSubview(discBackgroundImageView) // addSubview(coverImageView) addSubview(albumImageView) addSubview(discImageView) addSubview(maskImageView) // discBackgroundImageView.snp.makeConstraints { (make) in // make.edges.equalToSuperview() // } // coverImageView.snp.makeConstraints { (make) in // make.size.equalTo(discImageView).offset(-80) // make.center.equalToSuperview() // } albumImageView.snp.makeConstraints { (make) in make.size.equalTo(discImageView).offset(-80) make.center.equalToSuperview() } discImageView.snp.makeConstraints { (make) in make.size.equalToSuperview() make.center.equalToSuperview() } maskImageView.snp.makeConstraints { (make) in make.width.equalTo(discImageView).offset(-12) make.center.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setImage(url: URL?) { albumImageView.kf.setImage(with: url, placeholder: albumImageView.image ?? #imageLiteral(resourceName: "player_cover_default"), options: [.forceTransition, .transition(.fade(1))]) } }
mit
c2dba9bb868f1bacf8e4638f0ea6ad51
34.904762
130
0.613616
4.938865
false
false
false
false
IngmarStein/swift
stdlib/public/SDK/Contacts/Contacts.swift
4
1275
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Contacts import Foundation @available(macOS 10.11, iOS 9.0, *) extension CNError { /// One or more CNContact, CNGroup or CNContainer objects for which /// the error applies. public var affectedRecords: [AnyObject]? { return userInfo[CNErrorUserInfoAffectedRecordsKey] as? [AnyObject] } /// The record identifiers to which this error applies. public var affectedRecordIdentifiers: [String]? { return userInfo[CNErrorUserInfoAffectedRecordIdentifiersKey] as? [String] } /// The key paths associated with a given error. For validation /// errors this will contain key paths to specific object /// properties. public var keyPaths: [String]? { return userInfo[CNErrorUserInfoKeyPathsKey] as? [String] } }
apache-2.0
adeeae4335e080dcd8c27f1df210a8d5
35.428571
80
0.64549
4.757463
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Onboarding/Main/StudyGroupViewController.swift
1
12534
// // StudyGroupViewController.swift // HTWDD // // Created by Mustafa Karademir on 02.08.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import UIKit import Lottie import RxSwift import RxCocoa class StudyGroupViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var lblStudyGroups: UILabel! @IBOutlet weak var lblStudygroupDescription: UILabel! @IBOutlet weak var lblStudyGroupInformation: UILabel! @IBOutlet weak var userAnimationView: AnimationView! @IBOutlet weak var btnYear: UIButton! @IBOutlet weak var btnMajor: UIButton! @IBOutlet weak var btnGroup: UIButton! @IBOutlet weak var lblYear: UILabel! @IBOutlet weak var lblMajor: UILabel! @IBOutlet weak var lblGroup: UILabel! @IBOutlet weak var btnClose: UIButton! // MARK: - Properties weak var context: AppContext? private lazy var userAnimation: Animation? = { return Animation.named("UserGrey") }() weak var delegate: UIPageViewSwipeDelegate? var delegateClosure: (() -> Void)? = nil private let visualEffectView = UIVisualEffectView(effect: nil) private lazy var animator: UIViewPropertyAnimator = { return UIViewPropertyAnimator(duration: 0.4, curve: .easeInOut, animations: { self.visualEffectView.effect = UIBlurEffect(style: .regular) }) }() private var state = BehaviorRelay(value: State()) // MARK: - States private struct State { // MARK: - State.Study Year var years: [StudyYear]? var year: StudyYear? { didSet { if oldValue?.studyYear != year?.studyYear { major = nil group = nil } } } // MARK: - State.Study Courses var majors: [StudyCourse]? { guard let years = years, let year = year else { return nil } return years .first(where: { $0.studyYear == year.studyYear })? .studyCourses? .filter({ !$0.name.isEmpty }) } var major: StudyCourse? { didSet { if oldValue?.studyCourse != major?.studyCourse { group = nil } } } // MARK: - State.Study Groups var groups: [StudyGroup]? { guard let major = major, let majors = majors else { return nil } return majors.first(where: { $0.studyCourse == major.studyCourse })?.studyGroups } var group: StudyGroup? // MARK: - State.Completed var completed: Bool { return year != nil && major != nil && group != nil } } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setup() observe() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.userAnimationView.play() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if delegate == nil { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(25), execute: { [weak self] in guard let self = self else { return } self.animator.startAnimation() }) } } // MARK: - User Interaction @IBAction func onButtonsTouch(_ sender: UIButton) { let impactFeedbackgenerator = UIImpactFeedbackGenerator(style: .medium) impactFeedbackgenerator.prepare() impactFeedbackgenerator.impactOccurred() let selectionViewController = R.storyboard.onboarding.studyGroupSelectionViewController()!.also { $0.modalPresentationStyle = .overCurrentContext } switch sender { case btnYear: selectionViewController.data = state.value.years ?? [] selectionViewController.onSelect = { [weak self] selection in guard let self = self, let selection = selection else { return } if let selection = selection as? StudyYear { var mutableState = self.state.value mutableState.year = selection self.state.accept(mutableState) } } present(selectionViewController, animated: true, completion: nil) case btnMajor: selectionViewController.data = state.value.majors ?? [] selectionViewController.onSelect = { [weak self] selection in guard let self = self, let selection = selection else { return } if let selection = selection as? StudyCourse { var mutableState = self.state.value mutableState.major = selection self.state.accept(mutableState) } } present(selectionViewController, animated: true, completion: nil) case btnGroup: selectionViewController.data = state.value.groups ?? [] selectionViewController.onSelect = { [weak self] selection in guard let self = self, let selection = selection else { return } if let selection = selection as? StudyGroup { var mutableState = self.state.value mutableState.group = selection self.state.accept(mutableState) } } present(selectionViewController, animated: true, completion: nil) default: break } } @IBAction func onCancelTap(_ sender: UIButton) { UIImpactFeedbackGenerator(style: .medium) .also { $0.prepare() } .apply { $0.impactOccurred() } disolveWithAnimation() } private func disolveWithAnimation() { UIViewPropertyAnimator(duration: 0.25, curve: .easeInOut, animations: { [weak self] in guard let self = self else { return } self.visualEffectView.effect = nil }).apply { $0.startAnimation() } DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(170)) { [weak self] in guard let self = self else { return } self.dismiss(animated: true, completion: nil) } } } extension StudyGroupViewController { private func setup() { lblStudyGroups.apply { $0.text = R.string.localizable.onboardingStudygroupTitle() $0.textColor = UIColor.htw.Label.primary } lblStudygroupDescription.apply { $0.text = R.string.localizable.onboardingStudygroupDescription() $0.textColor = UIColor.htw.Label.primary } lblStudyGroupInformation.apply { $0.text = R.string.localizable.onboardingStudygroupInformation() $0.textColor = UIColor.htw.Label.secondary } userAnimationView.apply { $0.animation = userAnimation $0.contentMode = .scaleAspectFill $0.loopMode = .playOnce } btnYear.apply { $0.makeDropShadow() $0.setTitle(R.string.localizable.onboardingStudygroupYear(), for: .normal) $0.setState(with: .inactive) } lblYear.apply { $0.textColor = UIColor.htw.Label.secondary $0.font = UIFont.htw.Labels.secondary } btnMajor.apply { $0.makeDropShadow() $0.setTitle(R.string.localizable.onboardingStudygroupMajor(), for: .normal) $0.setState(with: .inactive) } lblMajor.apply { $0.textColor = UIColor.htw.Label.secondary $0.font = UIFont.htw.Labels.secondary } btnGroup.apply { $0.makeDropShadow() $0.setTitle(R.string.localizable.onboardingStudygroupGroup(), for: .normal) $0.setState(with: .inactive) } lblGroup.apply { $0.textColor = UIColor.htw.Label.secondary $0.font = UIFont.htw.Labels.secondary } if delegate == nil { btnClose.apply { $0.isHidden = false $0.setTitle(R.string.localizable.onboardingStudygroupNotnow(), for: .normal) } view.insertSubview(visualEffectView.also { $0.frame = self.view.frame }, at: 0) } } private func observe() { context?.apiService.requestStudyGroups() .asObservable() .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] data in guard let self = self else { return } var mutableState = self.state.value mutableState.years = data self.state.accept(mutableState) }, onError: { Log.error($0) }) .disposed(by: rx_disposeBag) state.asObservable() .map({ $0.years != nil }) .subscribe(onNext: { [weak self] hasYears in guard let self = self else { return } self.btnYear.setState(with: hasYears ? .active : .inactive) }, onError: { Log.error($0) }) .disposed(by: rx_disposeBag) state.asObservable() .map({ $0.year != nil }) .subscribe(onNext: { [weak self] hasYear in guard let self = self else { return } self.btnMajor.setState(with: hasYear ? .active : .inactive) self.lblYear.apply { $0.isHidden = !hasYear if let year = self.state.value.year { $0.text = "\(year.studyYear + 2000)" } } }, onError: { Log.error($0) }) .disposed(by: rx_disposeBag) state.asObservable() .map({ $0.major != nil }) .subscribe(onNext: { [weak self] hasMajor in guard let self = self else { return } self.btnGroup.setState(with: hasMajor ? .active : .inactive) self.lblMajor.apply { $0.isHidden = !hasMajor if let major = self.state.value.major { $0.text = "\(major.name.nilWhenEmpty ?? String("---"))\n\(major.studyCourse)" } } }, onError: { Log.error($0) }) .disposed(by: rx_disposeBag) state.asObservable() .map({ $0.group != nil }) .subscribe(onNext: { [weak self] hasGroup in guard let self = self else { return } self.lblGroup.apply { $0.isHidden = !hasGroup if let group = self.state.value.group { $0.text = "\(group.name)\n\(group.studyGroup)" } } }, onError: { Log.error($0) }) .disposed(by: rx_disposeBag) state.asObservable() .map({ $0.completed }) .subscribe(onNext: { [weak self] (isCompleted: Bool) in guard let self = self else { return } if isCompleted { KeychainService.shared.storeStudyToken(year: self.state.value.year?.studyYear.description, major: self.state.value.major?.studyCourse, group: self.state.value.group?.studyGroup, graduation: self.state.value.group?.name) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(750), execute: { self.delegate?.next(animated: true) if let delegateClosure = self.delegateClosure { delegateClosure() self.disolveWithAnimation() } }) } }, onError: { Log.error($0) }) .disposed(by: rx_disposeBag) } }
gpl-2.0
9ff1a9661912b2cf87f89337c2004195
36.523952
110
0.52669
4.963564
false
false
false
false
stephengazzard/physicsLightGame
PhysicsLightGame/PhysicsLightGame/GameViewController.swift
1
2739
// // GameViewController.swift // PhysicsLightGame // // Created by Stephen Gazzard on 2014-08-31. // Copyright (c) 2014 Broken Kings. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil) var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { var currentScene : GameScene? = nil @IBOutlet var winLabel : UILabel? = nil @IBOutlet var lightButton : UIButton? = nil override func viewDidLoad() { super.viewDidLoad() loadLevel(0) } func loadLevel(index : NSInteger) -> Void { if let scene = GameScene.unarchiveFromFile("Level\(index)") as? GameScene { // Configure the view. let skView = self.view as SKView /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill scene.owningViewController = self scene.levelIndex = index skView.presentScene(scene) self.winLabel?.hidden = true self.currentScene = scene } else { loadLevel(0) } } func showWinLabel() -> Void { self.winLabel?.hidden = false } func setLightButtonVisible(visible : Bool) { self.lightButton?.hidden = !visible } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw()) } else { return Int(UIInterfaceOrientationMask.All.toRaw()) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func dropLight() -> Void { self.currentScene?.dropLight() } }
gpl-2.0
7056fd9481489677ce2ac721ffa19085
27.831579
110
0.624315
5.197343
false
false
false
false
tangplin/JSON2Anything
JSON2Anything/Source/Extensions/Swift+J2A.swift
1
2919
// // Swift+J2A.swift // // Copyright (c) 2014 Pinglin Tang. // // 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. extension Int: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Int? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.integerValue } else if let o_s = o as? NSString { return o_s.integerValue } else { return nil } } } extension Float: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Float? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.floatValue } else if let o_s = o as? NSString { return o_s.floatValue } else { return nil } } } extension Double: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Double? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.doubleValue } else if let o_s = o as? NSString { return o_s.doubleValue } else { return nil } } } extension Bool: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Bool? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.boolValue } else if let o_s = o as? NSString { return o_s.boolValue } else { return nil } } }
mit
a6f5d92d70b03ecc5a5bb43fcadcd9ab
27.627451
80
0.594724
4.483871
false
false
false
false
SwiftAndroid/swift
stdlib/public/core/ArrayBufferProtocol.swift
1
7606
//===--- ArrayBufferProtocol.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// The underlying buffer for an ArrayType conforms to /// `_ArrayBufferProtocol`. This buffer does not provide value semantics. public protocol _ArrayBufferProtocol : MutableCollection { /// The type of elements stored in the buffer. associatedtype Element /// Create an empty buffer. init() /// Adopt the entire buffer, presenting it at the provided `startIndex`. init(_ buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int) /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer past-the-end of the /// just-initialized memory. func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> /// Get or set the index'th element. subscript(index: Int) -> Element { get nonmutating set } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self` /// buffer store `minimumCapacity` elements, returns that buffer. /// Otherwise, returns `nil`. /// /// - Note: The result's firstElementAddress may not match ours, if we are a /// _SliceBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. @warn_unused_result mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? /// Returns `true` iff this buffer is backed by a uniquely-referenced mutable /// _ContiguousArrayBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. @warn_unused_result mutating func isMutableAndUniquelyReferenced() -> Bool /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @warn_unused_result func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? /// Replace the given `subRange` with the first `newCount` elements of /// the given collection. /// /// - Precondition: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer`. mutating func replace<C : Collection where C.Iterator.Element == Element>( subRange: Range<Int>, with newCount: Int, elementsOf newValues: C ) /// Returns a `_SliceBuffer` containing the elements in `bounds`. subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. func withUnsafeBufferPointer<R>( @noescape _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. mutating func withUnsafeMutableBufferPointer<R>( @noescape _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R /// The number of elements the buffer stores. var count: Int { get set } /// The number of elements the buffer can store without reallocation. var capacity: Int { get } /// An object that keeps the elements stored in this buffer alive. var owner: AnyObject { get } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. var firstElementAddress: UnsafeMutablePointer<Element> { get } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { get } /// Returns a base address to which you can add an index `i` to get the /// address of the corresponding element at `i`. var subscriptBaseAddress: UnsafeMutablePointer<Element> { get } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. var identity: UnsafePointer<Void> { get } var startIndex: Int { get } } extension _ArrayBufferProtocol { public var subscriptBaseAddress: UnsafeMutablePointer<Element> { return firstElementAddress } public mutating func replace< C : Collection where C.Iterator.Element == Element >( subRange: Range<Int>, with newCount: Int, elementsOf newValues: C ) { _sanityCheck(startIndex == 0, "_SliceBuffer should override this function.") let oldCount = self.count let eraseCount = subRange.count let growth = newCount - eraseCount self.count = oldCount + growth let elements = self.subscriptBaseAddress let oldTailIndex = subRange.endIndex let oldTailStart = elements + oldTailIndex let newTailIndex = oldTailIndex + growth let newTailStart = oldTailStart + growth let tailCount = oldCount - subRange.endIndex if growth > 0 { // Slide the tail part of the buffer forwards, in reverse order // so as not to self-clobber. newTailStart.moveInitializeBackwardFrom(oldTailStart, count: tailCount) // Assign over the original subRange var i = newValues.startIndex for j in subRange { elements[j] = newValues[i] i._successorInPlace() } // Initialize the hole left by sliding the tail forward for j in oldTailIndex..<newTailIndex { (elements + j).initialize(with: newValues[i]) i._successorInPlace() } _expectEnd(i, newValues) } else { // We're not growing the buffer // Assign all the new elements into the start of the subRange var i = subRange.startIndex var j = newValues.startIndex for _ in 0..<newCount { elements[i] = newValues[j] i._successorInPlace() j._successorInPlace() } _expectEnd(j, newValues) // If the size didn't change, we're done. if growth == 0 { return } // Move the tail backward to cover the shrinkage. let shrinkage = -growth if tailCount > shrinkage { // If the tail length exceeds the shrinkage // Assign over the rest of the replaced range with the first // part of the tail. newTailStart.moveAssignFrom(oldTailStart, count: shrinkage) // Slide the rest of the tail back oldTailStart.moveInitializeFrom( oldTailStart + shrinkage, count: tailCount - shrinkage) } else { // Tail fits within erased elements // Assign over the start of the replaced range with the tail newTailStart.moveAssignFrom(oldTailStart, count: tailCount) // Destroy elements remaining after the tail in subRange (newTailStart + tailCount).deinitialize( count: shrinkage - tailCount) } } } }
apache-2.0
859a7196b2d7f458a817311d0fa08dea
35.567308
80
0.677623
4.835346
false
false
false
false
davidjinhan/ButtonMenuPopup
ButtonMenuPopup/ButtonModel.swift
1
1236
// // ButtonModel.swift // ButtonMenuPopup // // Created by HanJin on 2017. 3. 27.. // Copyright © 2017년 DavidJinHan. All rights reserved. // import Foundation import RxSwift enum ButtonType { case fruit, vegetable var buttonStrings: [String] { switch self { case .fruit: return [ "citrus", "pear", "apple", "avocado", "banana" ] case .vegetable: return [ "corn", "tomato", "mushroom", "carrot" ] } } } struct ButtonModel { var buttonImage: UIImage var buttonTitle: String var buttonColor: UIColor var type: ButtonType var isVisible: Variable<Bool> init(image: String, title: String, color: UIColor, type: ButtonType, isVisible: Bool = true) { self.buttonImage = UIImage(named: image)!.withRenderingMode(.alwaysTemplate) self.buttonTitle = title self.buttonColor = color self.type = type self.isVisible = Variable(isVisible) } } extension ButtonModel: Equatable { } func == (lhs: ButtonModel, rhs: ButtonModel) -> Bool { return (lhs.buttonTitle == rhs.buttonTitle && lhs.isVisible.value == rhs.isVisible.value) }
mit
8d029852fdbf75bca15758ccb0a884ce
23.176471
98
0.602595
4.11
false
false
false
false
SearchDream/iOS-9-Sampler
iOS9Sampler/SampleViewControllers/ContactsViewController.swift
2
7232
// // ContactsViewController.swift // iOS9Sampler // // Created by manhattan918 on 2015/9/20. // Copyright © 2015 manhattan918. All rights reserved. // import UIKit import Contacts class ContactsViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak fileprivate var tableView: UITableView! @IBOutlet weak fileprivate var searchBar: UISearchBar! fileprivate var contacts = [CNContact]() fileprivate var authStatus: CNAuthorizationStatus = .denied { didSet { // switch enabled search bar, depending contacts permission DispatchQueue.main.async { self.searchBar.isUserInteractionEnabled = self.authStatus == .authorized if self.authStatus == .authorized { // all search self.contacts = self.fetchContacts("") self.tableView.reloadData() } } } } fileprivate let kCellID = "Cell" // ========================================================================= // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() checkAuthorization() tableView.register(UITableViewCell.self, forCellReuseIdentifier: kCellID) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // ========================================================================= // MARK: - UISearchBarDelegate func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { contacts = fetchContacts(searchText) tableView.reloadData() } // ========================================================================= //MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kCellID, for: indexPath) let contact = contacts[indexPath.row] // get the full name let fullName = CNContactFormatter.string(from: contact, style: .fullName) ?? "NO NAME" cell.textLabel?.text = fullName return cell } // ========================================================================= //MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteActionHandler = { (action: UITableViewRowAction, index: IndexPath) in let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { [unowned self] (action: UIAlertAction) in // set the data to be deleted let request = CNSaveRequest() let contact = self.contacts[index.row].mutableCopy() as! CNMutableContact request.delete(contact) do { // save let fullName = CNContactFormatter.string(from: contact, style: .fullName) ?? "NO NAME" let store = CNContactStore() try store.execute(request) NSLog("\(fullName) Deleted") // update table self.contacts.remove(at: index.row) DispatchQueue.main.async(execute: { self.tableView.deleteRows(at: [index], with: .fade) }) } catch let error as NSError { NSLog("Delete error \(error.localizedDescription)") } }) let cancelAction = UIAlertAction(title: "CANCEL", style: UIAlertAction.Style.default, handler: { [unowned self] (action: UIAlertAction) in self.tableView.isEditing = false }) // show alert self.showAlert(title: "Delete Contact", message: "OK?", actions: [okAction, cancelAction]) } return [UITableViewRowAction(style: .default, title: "Delete", handler: deleteActionHandler)] } // ========================================================================= // MARK: - IBAction @IBAction func tapped(_ sender: AnyObject) { view.endEditing(true) } // ========================================================================= // MARK: - Helpers fileprivate func checkAuthorization() { // get current status let status = CNContactStore.authorizationStatus(for: .contacts) authStatus = status switch status { case .notDetermined: // case of first access CNContactStore().requestAccess(for: .contacts) { [unowned self] (granted, error) in if granted { NSLog("Permission allowed") self.authStatus = .authorized } else { NSLog("Permission denied") self.authStatus = .denied } } case .restricted, .denied: NSLog("Unauthorized") let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: { (action: UIAlertAction) in let url = URL(string: UIApplication.openSettingsURLString) UIApplication.shared.openURL(url!) }) showAlert( title: "Permission Denied", message: "You have not permission to access contacts. Please allow the access the Settings screen.", actions: [okAction, settingsAction]) case .authorized: NSLog("Authorized") } } // fetch the contact of matching names fileprivate func fetchContacts(_ name: String) -> [CNContact] { let store = CNContactStore() do { let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]) if name.isEmpty { // all search request.predicate = nil } else { request.predicate = CNContact.predicateForContacts(matchingName: name) } var contacts = [CNContact]() try store.enumerateContacts(with: request, usingBlock: { (contact, error) in contacts.append(contact) }) return contacts } catch let error as NSError { NSLog("Fetch error \(error.localizedDescription)") return [] } } fileprivate func showAlert(title: String, message: String, actions: [UIAlertAction]) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) for action in actions { alert.addAction(action) } DispatchQueue.main.async(execute: { [unowned self] () in self.present(alert, animated: true, completion: nil) }) } }
mit
c8448a8401efc7274a3d437ff50bdca1
34.965174
150
0.55388
5.750994
false
false
false
false
mikegilroy/SegmentedControl
SegmentedControlDemo/SegmentedControlDemo/ViewController.swift
1
1187
// // ViewController.swift // SegmentedControlDemo // // Created by Mike Gilroy on 01/03/2017. // Copyright © 2017 Mike Gilroy. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var controlContainerView: UIView! override func viewDidLoad() { super.viewDidLoad() setupSegmentedControl() } func setupSegmentedControl() { let segmentedControl = SegmentedControl(frame: controlContainerView.bounds, tabIcons: [#imageLiteral(resourceName: "beer_icon"), #imageLiteral(resourceName: "bar_icon"), #imageLiteral(resourceName: "night_club"), #imageLiteral(resourceName: "restaurant")], controlColor: UIColor.orange, selectedTabColor: UIColor.white, tabTintColor: UIColor.white) segmentedControl.delegate = self controlContainerView.addSubview(segmentedControl) } } extension ViewController: SegmentedControlDelegate { func tabSelected(atIndex index: Int) { messageLabel.alpha = 1 messageLabel.text = "You selected tab number \(index + 1) ☝️" UIView.animate(withDuration: 1, delay: 1, options: .curveEaseInOut, animations: { self.messageLabel.alpha = 0 }) } }
mit
5d5bc09fe7af6aaa1da081afb08aec0f
28.55
350
0.753807
4.104167
false
false
false
false
Polidea/RxBluetoothKit
Source/Characteristic.swift
1
9538
import Foundation import RxSwift import CoreBluetooth /// Characteristic is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with [CBCharacteristic](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/) public class Characteristic { /// Intance of CoreBluetooth characteristic class public let characteristic: CBCharacteristic /// Service which contains this characteristic public let service: Service /// Current value of characteristic. If value is not present - it's `nil`. public var value: Data? { return characteristic.value } /// The Bluetooth UUID of the `Characteristic` instance. public var uuid: CBUUID { return characteristic.uuid } /// Flag which is set to true if characteristic is currently notifying public var isNotifying: Bool { return characteristic.isNotifying } /// Properties of characteristic. For more info about this refer to [CBCharacteristicProperties](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/#//apple_ref/c/tdef/CBCharacteristicProperties) public var properties: CBCharacteristicProperties { return characteristic.properties } /// Value of this property is an array of `Descriptor` objects. They provide more detailed information about characteristics value. public var descriptors: [Descriptor]? { return characteristic.descriptors?.map { Descriptor(descriptor: $0, characteristic: self) } } init(characteristic: CBCharacteristic, service: Service) { self.characteristic = characteristic self.service = service } convenience init(characteristic: CBCharacteristic, peripheral: Peripheral) { let service = Service(peripheral: peripheral, service: characteristic.service) self.init(characteristic: characteristic, service: service) } /// Function that triggers descriptors discovery for characteristic. /// - returns: `Single` that emits `next` with array of `Descriptor` instances, once they're discovered. /// /// Observable can ends with following errors: /// * `BluetoothError.descriptorsDiscoveryFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func discoverDescriptors() -> Single<[Descriptor]> { return service.peripheral.discoverDescriptors(for: self) } /// Function that allow to observe writes that happened for characteristic. /// - Returns: `Observable` that emits `next` with `Characteristic` instance every time when write has happened. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `BluetoothError.characteristicWriteFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func observeWrite() -> Observable<Characteristic> { return service.peripheral.observeWrite(for: self) } /// Function that allows to know the exact time, when isNotyfing value has changed on a characteristic. /// /// - returns: `Observable` emitting `Characteristic` when isNoytfing value has changed. /// /// Observable can ends with following errors: /// * `BluetoothError.characteristicSetNotifyValueFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func observeNotifyValue() -> Observable<Characteristic> { return service.peripheral.observeNotifyValue(for: self) } /// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made. /// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/swift/enum/c:@E@CBCharacteristicWriteType), so be sure to check this out before usage of the method. /// - parameter data: `Data` that'll be written to the `Characteristic` /// - parameter type: Type of write operation. Possible values: `.withResponse`, `.withoutResponse` /// - returns: `Single` whose emission depends on `CBCharacteristicWriteType` passed to the function call. /// Behavior is following: /// /// - `withResponse` - `Observable` emits `next` with `Characteristic` instance write was confirmed without any errors. /// If any problem has happened, errors are emitted. /// - `withoutResponse` - `Observable` emits `next` with `Characteristic` instance once write was called. /// Result of this call is not checked, so as a user you are not sure /// if everything completed successfully. Errors are not emitted /// /// Observable can ends with following errors: /// * `BluetoothError.characteristicWriteFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func writeValue(_ data: Data, type: CBCharacteristicWriteType) -> Single<Characteristic> { return service.peripheral.writeValue(data, for: self, type: type) } /// Function that allow to observe value updates for `Characteristic` instance. /// - Returns: `Observable` that emits `Next` with `Characteristic` instance every time when value has changed. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `BluetoothError.characteristicReadFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func observeValueUpdate() -> Observable<Characteristic> { return service.peripheral.observeValueUpdate(for: self) } /// Function that triggers read of current value of the `Characteristic` instance. /// Read is called after subscription to `Observable` is made. /// - Returns: `Single` which emits `next` with given characteristic when value is ready to read. /// /// Observable can ends with following errors: /// * `BluetoothError.characteristicReadFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func readValue() -> Single<Characteristic> { return service.peripheral.readValue(for: self) } /// Setup characteristic notification in order to receive callbacks when given characteristic has been changed. /// Returned observable will emit `Characteristic` on every notification change. /// It is possible to setup more observables for the same characteristic and the lifecycle of the notification will be shared among them. /// /// Notification is automaticaly unregistered once this observable is unsubscribed /// /// - returns: `Observable` emitting `next` with `Characteristic` when given characteristic has been changed. /// /// This is **infinite** stream of values. /// /// Observable can ends with following errors: /// * `BluetoothError.characteristicReadFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func observeValueUpdateAndSetNotification() -> Observable<Characteristic> { return service.peripheral.observeValueUpdateAndSetNotification(for: self) } } extension Characteristic: Equatable {} extension Characteristic: UUIDIdentifiable {} /// Compare two characteristics. Characteristics are the same when their UUIDs are the same. /// /// - parameter lhs: First characteristic to compare /// - parameter rhs: Second characteristic to compare /// - returns: True if both characteristics are the same. public func == (lhs: Characteristic, rhs: Characteristic) -> Bool { return lhs.characteristic == rhs.characteristic }
apache-2.0
1a627680425b2cb5e80110d125074b93
48.677083
292
0.719124
5.346413
false
false
false
false
uber/RIBs
ios/tutorials/tutorial3/TicTacToe/TicTacToe/TicTacToeInteractor.swift
1
4414
// // Copyright (c) 2017. Uber Technologies // // 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 RIBs import RxSwift protocol TicTacToeRouting: ViewableRouting { // TODO: Declare methods the interactor can invoke to manage sub-tree via the router. } protocol TicTacToePresentable: Presentable { var listener: TicTacToePresentableListener? { get set } func setCell(atRow row: Int, col: Int, withPlayerType playerType: PlayerType) func announce(winner: PlayerType) } protocol TicTacToeListener: AnyObject { func gameDidEnd() } final class TicTacToeInteractor: PresentableInteractor<TicTacToePresentable>, TicTacToeInteractable, TicTacToePresentableListener { weak var router: TicTacToeRouting? weak var listener: TicTacToeListener? // TODO: Add additional dependencies to constructor. Do not perform any logic // in constructor. override init(presenter: TicTacToePresentable) { super.init(presenter: presenter) presenter.listener = self } override func didBecomeActive() { super.didBecomeActive() initBoard() } override func willResignActive() { super.willResignActive() // TODO: Pause any business logic. } // MARK: - TicTacToePresentableListener func placeCurrentPlayerMark(atRow row: Int, col: Int) { guard board[row][col] == nil else { return } let currentPlayer = getAndFlipCurrentPlayer() board[row][col] = currentPlayer presenter.setCell(atRow: row, col: col, withPlayerType: currentPlayer) if let winner = checkWinner() { presenter.announce(winner: winner) } } func closeGame() { listener?.gameDidEnd() } // MARK: - Private private var currentPlayer = PlayerType.player1 private var board = [[PlayerType?]]() private func initBoard() { for _ in 0..<GameConstants.rowCount { board.append([nil, nil, nil]) } } private func getAndFlipCurrentPlayer() -> PlayerType { let currentPlayer = self.currentPlayer self.currentPlayer = currentPlayer == .player1 ? .player2 : .player1 return currentPlayer } private func checkWinner() -> PlayerType? { // Rows. for row in 0..<GameConstants.rowCount { guard let assumedWinner = board[row][0] else { continue } var winner: PlayerType? = assumedWinner for col in 1..<GameConstants.colCount { if assumedWinner.rawValue != board[row][col]?.rawValue { winner = nil break } } if let winner = winner { return winner } } // Cols. for col in 0..<GameConstants.colCount { guard let assumedWinner = board[0][col] else { continue } var winner: PlayerType? = assumedWinner for row in 1..<GameConstants.rowCount { if assumedWinner.rawValue != board[row][col]?.rawValue { winner = nil break } } if let winner = winner { return winner } } // Diagonal. guard let p11 = board[1][1] else { return nil } if let p00 = board[0][0], let p22 = board[2][2] { if p00.rawValue == p11.rawValue && p11.rawValue == p22.rawValue { return p11 } } if let p02 = board[0][2], let p20 = board[2][0] { if p02.rawValue == p11.rawValue && p11.rawValue == p20.rawValue { return p11 } } return nil } } struct GameConstants { static let rowCount = 3 static let colCount = 3 }
apache-2.0
dd786d55227ea2a31f45cb02d1018290
27.849673
131
0.592207
4.661035
false
false
false
false
podverse/podverse-ios
Podverse/MediaPlayerViewController.swift
1
29585
// // MediaPlayerViewController.swift // Podverse // // Created by Mitchell Downey on 5/17/17. // Copyright © 2017 Podverse LLC. All rights reserved. // import AVFoundation import CoreData import StreamingKit import UIKit class MediaPlayerViewController: PVViewController { let reachability = PVReachability.shared var timer: Timer? weak var currentChildViewController: UIViewController? private let aboutClipsStoryboardId = "AboutPlayingItemVC" private let clipsListStoryBoardId = "ClipsListVC" @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var clipsContainerView: UIView! @IBOutlet weak var currentTime: UILabel! @IBOutlet weak var continuousPlayback: UIButton! @IBOutlet weak var duration: UILabel! @IBOutlet weak var episodePubDate: UILabel! @IBOutlet weak var episodeTitle: UILabel! @IBOutlet weak var image: UIImageView! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var play: UIButton! @IBOutlet weak var podcastTitle: UILabel! @IBOutlet weak var progress: UISlider! @IBOutlet weak var speed: UIButton! @IBOutlet weak var startTimeFlagView: UIView! @IBOutlet weak var endTimeFlagView: UIView! @IBOutlet weak var startTimeLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var endTimeLeadingConstraint: NSLayoutConstraint! override func viewDidLoad() { let share = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: self, action: #selector(showShareMenu)) let makeClip = UIBarButtonItem(image: UIImage(named:"clip"), style: .plain, target: self, action: #selector(showMakeClip)) let addToPlaylist = UIBarButtonItem(image: UIImage(named:"add"), style: .plain, target: self, action: #selector(showAddToPlaylist)) navigationItem.rightBarButtonItems = [share, addToPlaylist, makeClip] self.progress.setThumbImage(#imageLiteral(resourceName: "SliderCurrentPosition"), for: .normal) self.tabBarController?.hidePlayerView() addObservers() self.activityIndicator.startAnimating() setupTimer() updateContinuousPlaybackIcon() // If autoplaying, we don't want the flags to appear immediately, as the pvMediaPlayer may still have an old duration value, and the flags will appear relative to the old duration. // If not autoplaying, then the pvMediaPlayer.duration should still be accurate, and we can set the clip flags immediately. if !pvMediaPlayer.shouldAutoplayOnce && !pvMediaPlayer.shouldAutoplayAlways { setupClipFlags() } else if pvMediaPlayer.isItemLoaded && pvMediaPlayer.isInClipTimeRange() { setupClipFlags() } if (self.pvMediaPlayer.isDataAvailable) { populatePlayerInfo() } else { clearPlayerData() } setupContainerView() } deinit { removeObservers() removeTimer() } override func viewWillAppear(_ animated: Bool) { navigationController?.interactivePopGestureRecognizer?.isEnabled = false self.pvMediaPlayer.delegate = self togglePlayIcon() updateSpeedLabel() updateTime() } override func viewWillDisappear(_ animated: Bool) { navigationController?.interactivePopGestureRecognizer?.isEnabled = true } fileprivate func addObservers() { NotificationCenter.default.addObserver(self, selector: #selector(hideClipData), name: .hideClipData, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleDidFinishPlaying), name: .playerHasFinished, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(setupClipFlags), name: .clipUpdated, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(hideClipData), name: .clipDeleted, object: nil) } fileprivate func removeObservers() { NotificationCenter.default.removeObserver(self, name: .hideClipData, object: nil) NotificationCenter.default.removeObserver(self, name: .playerHasFinished, object: nil) NotificationCenter.default.removeObserver(self, name: .clipUpdated, object: nil) NotificationCenter.default.removeObserver(self, name: .clipDeleted, object: nil) } @IBAction func pageControlAction(_ sender: Any) { if let sender = sender as? UIPageControl { if sender.currentPage == 1 { showClipsContainerView() } else { showAboutView() } } } @IBAction func sliderAction(_ sender: Any, forEvent event: UIEvent) { if let sender = sender as? UISlider, let touchEvent = event.allTouches?.first { switch touchEvent.phase { case .began: removeTimer() case .moved: if let duration = self.pvMediaPlayer.duration { let newTime = Double(sender.value) * duration self.currentTime.text = PVTimeHelper.convertIntToHMSString(time: Int(newTime)) } case .ended: if let duration = self.pvMediaPlayer.duration { let newTime = Double(sender.value) * duration self.pvMediaPlayer.seek(toTime: newTime) updateTime() } setupTimer() default: break } } } @IBAction func play(_ sender: Any) { self.pvMediaPlayer.playOrPause() } @IBAction func timeJumpBackward(_ sender: Any) { let newTime = self.pvMediaPlayer.progress - 15 if newTime >= 14 { self.pvMediaPlayer.seek(toTime: newTime) } else { self.pvMediaPlayer.seek(toTime: 0) } updateTime() } @IBAction func timeJumpForward(_ sender: Any) { let newTime = self.pvMediaPlayer.progress + 15 self.pvMediaPlayer.seek(toTime: newTime) updateTime() } @IBAction func changeSpeed(_ sender: Any) { switch self.pvMediaPlayer.playerSpeedRate { case .regular: self.pvMediaPlayer.playerSpeedRate = .timeAndQuarter break case .timeAndQuarter: self.pvMediaPlayer.playerSpeedRate = .timeAndHalf break case .timeAndHalf: self.pvMediaPlayer.playerSpeedRate = .double break case .double: self.pvMediaPlayer.playerSpeedRate = .half case .half: self.pvMediaPlayer.playerSpeedRate = .threeQuarts break case .threeQuarts: self.pvMediaPlayer.playerSpeedRate = .regular break } updateSpeedLabel() } @objc func pause() { pvMediaPlayer.pause() } @IBAction func toggleContinuousPlayback(_ sender: Any) { self.pvMediaPlayer.toggleShouldPlayContinuously() updateContinuousPlaybackIcon() } @objc func handleDidFinishPlaying () { if let nowPlayingItem = self.pvMediaPlayer.nowPlayingItem, !nowPlayingItem.isClip() { navigationController?.popViewController(animated: true) } } fileprivate func setupContainerView() { self.childViewControllers.forEach({ $0.willMove(toParentViewController: nil) $0.view.removeFromSuperview() $0.removeFromParentViewController() }) self.currentChildViewController = nil if let currentVC = self.storyboard?.instantiateViewController(withIdentifier: self.aboutClipsStoryboardId) { self.currentChildViewController = currentVC self.currentChildViewController?.view.translatesAutoresizingMaskIntoConstraints = false self.addChildViewController(currentVC) self.addSubview(subView: currentVC.view, toView: self.clipsContainerView) } let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(MediaPlayerViewController.showClipsContainerView)) let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(MediaPlayerViewController.showAboutView)) swipeLeft.direction = .left swipeRight.direction = .right self.clipsContainerView.addGestureRecognizer(swipeLeft) self.clipsContainerView.addGestureRecognizer(swipeRight) self.clipsContainerView.layer.borderColor = UIColor.darkGray.cgColor self.clipsContainerView.layer.borderWidth = 1.0 self.pageControl.currentPage = 0 } fileprivate func updateContinuousPlaybackIcon () { if UserDefaults.standard.bool(forKey: kShouldPlayContinuously) { self.continuousPlayback.setTitle("On", for: .normal) } else { self.continuousPlayback.setTitle("Off", for: .normal) } } func togglePlayIcon() { // Grab audioPlayer each time to ensure we are checking the correct state let audioPlayer = PVMediaPlayer.shared.audioPlayer DispatchQueue.main.async { if !self.pvMediaPlayer.isDataAvailable { self.activityIndicator.isHidden = false self.play.isHidden = true } else if audioPlayer.state == .stopped || audioPlayer.state == .paused { self.activityIndicator.isHidden = true self.play.setImage(UIImage(named:"play"), for: .normal) self.play.tintColor = UIColor.white self.play.isHidden = false } else if audioPlayer.state == .error { self.activityIndicator.isHidden = true self.play.setImage(UIImage(named:"playerror"), for: .normal) self.play.tintColor = UIColor.red self.play.isHidden = false } else if audioPlayer.state == .playing && !self.pvMediaPlayer.shouldSetupClip { self.activityIndicator.isHidden = true self.play.setImage(UIImage(named:"pause"), for: .normal) self.play.tintColor = UIColor.white self.play.isHidden = false } else if audioPlayer.state == .buffering || self.pvMediaPlayer.shouldSetupClip { self.activityIndicator.isHidden = false self.play.isHidden = true } else { self.activityIndicator.isHidden = true self.play.setImage(UIImage(named:"play"), for: .normal) self.play.tintColor = UIColor.white self.play.isHidden = false } } } func populatePlayerInfo() { if let item = self.pvMediaPlayer.nowPlayingItem { self.podcastTitle.text = item.podcastTitle?.stringByDecodingHTMLEntities() self.episodeTitle.text = item.episodeTitle?.stringByDecodingHTMLEntities() if let pubDate = item.episodePubDate { self.episodePubDate.text = pubDate.toShortFormatString() } else { self.episodePubDate.text = "" } self.image.image = Podcast.retrievePodcastImage(podcastImageURLString: item.podcastImageUrl, feedURLString: item.podcastFeedUrl, completion: { image in self.image.image = image }) if let dur = self.pvMediaPlayer.duration { duration.text = Int64(dur).toMediaPlayerString() } } } func clearPlayerData() { self.podcastTitle.text = nil self.episodeTitle.text = nil self.episodePubDate.text = nil self.image.image = nil self.duration.text = nil self.pvMediaPlayer.audioPlayer.stop() self.pvMediaPlayer.clearPlayingItem() self.pageControl.currentPage = 0 clearTime() togglePlayIcon() } @objc func updateTime () { DispatchQueue.main.async { var playbackPosition = 0.0 if self.pvMediaPlayer.progress > 0 { playbackPosition = self.pvMediaPlayer.progress } else if let dur = self.pvMediaPlayer.duration { playbackPosition = Double(self.progress.value) * dur } if (!self.pvMediaPlayer.isDataAvailable) { self.currentTime.text = "--:--" } else { self.currentTime.text = Int64(playbackPosition).toMediaPlayerString() } if let dur = self.pvMediaPlayer.duration { self.duration.text = Int64(dur).toMediaPlayerString() self.progress.value = Float(playbackPosition / dur) } } } func clearTime () { self.progress.value = 0.0 self.duration.text = "--:--" self.currentTime.text = "--:--" } func showPendingTime() { self.currentTime.text = "--:--" self.duration.text = "--:--" } func setupTimer () { self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true) } func removeTimer () { if let timer = self.timer { timer.invalidate() } self.timer = nil } func updateSpeedLabel() { DispatchQueue.main.async { self.speed.setImage(self.pvMediaPlayer.playerSpeedRate.speedImage, for: .normal) } } func presentLogin() { let storyboard = UIStoryboard(name: "Main", bundle: nil) if let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginVC") as? LoginViewController { self.present(loginVC, animated: true, completion: nil) } } @objc func showAddToPlaylist() { if !self.pvMediaPlayer.isDataAvailable { return } if !checkForConnectivity() { self.showInternetNeededAlertWithDescription(message: "You must be connected to the internet to add to playlists.") return } guard PVAuth.userIsLoggedIn else { let alert = UIAlertController(title: "Login Required", message: "You must be logged in to create playlists.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) alert.addAction(UIAlertAction(title: "Login", style: .default, handler: { action in self.presentLogin() })) self.present(alert, animated: true, completion: nil) return } self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"Player", style:.plain, target:nil, action:nil) if let item = self.playerHistoryManager.historyItems.first, item.mediaRefId == nil { self.performSegue(withIdentifier: "Show Add to Playlist", sender: "Full Episode") return } let addToPlaylistActions = UIAlertController(title: "Add to a Playlist", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet) addToPlaylistActions.addAction(UIAlertAction(title: "Full Episode", style: .default, handler: { action in self.performSegue(withIdentifier: "Show Add to Playlist", sender: "Full Episode") })) addToPlaylistActions.addAction(UIAlertAction(title: "Current Clip", style: .default, handler: { action in self.performSegue(withIdentifier: "Show Add to Playlist", sender: "Current Clip") })) addToPlaylistActions.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(addToPlaylistActions, animated: true, completion: nil) } func segueToRequestPodcastForm() { if let webKitVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "WebKitVC") as? WebKitViewController { webKitVC.urlString = kFormRequestPodcastUrl self.navigationController?.pushViewController(webKitVC, animated: true) } } @objc func showMakeClip() { if !self.pvMediaPlayer.isDataAvailable { return } if !checkForConnectivity() { self.showInternetNeededAlertWithDescription(message: "You must be connected to the internet to make clips.") return } if let item = self.playerHistoryManager.historyItems.first { if item.podcastId == nil { let message = "This podcast was added by RSS feed. Please request to add it to podverse.fm to enable clip making." let cantMakeClipActions = UIAlertController(title: "Can't Make Clip", message: message, preferredStyle: .alert) cantMakeClipActions.addAction(UIAlertAction(title: "Request", style: .default, handler: { action in self.segueToRequestPodcastForm() })) cantMakeClipActions.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(cantMakeClipActions, animated: true, completion: nil) } self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"Player", style:.plain, target:nil, action:nil) self.performSegue(withIdentifier: "Show Make Clip Time", sender: self) } } @objc func showShareMenu() { if !self.pvMediaPlayer.isDataAvailable { return } if !checkForConnectivity() { self.showInternetNeededAlertWithDescription(message: "You must be connected to the internet to share links.") return } if let item = self.playerHistoryManager.historyItems.first { // If a mediaRefId is present, then allow the option to copy the link to the Episode or Clip. Else, copy the link to the Episode. if let mediaRefId = item.mediaRefId { let shareActions = UIAlertController(title: "Share", message: nil, preferredStyle: .actionSheet) shareActions.addAction(UIAlertAction(title: "Episode Link", style: .default, handler: { action in self.handleEpisodeLink(item) })) shareActions.addAction(UIAlertAction(title: "Clip Link", style: .default, handler: { action in self.loadActvityViewWithClipLink(mediaRefId:mediaRefId) })) shareActions.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(shareActions, animated: true, completion: nil) } else { handleEpisodeLink(item) } } } func handleEpisodeLink(_ item: PlayerHistoryItem) { if let episodeId = item.episodeId { self.loadActivityViewWithEpisodeLink(episodeId: episodeId) } else if let mediaUrl = item.episodeMediaUrl { Episode.retrieveEpisodeIdFromServer(mediaUrl: mediaUrl) { episodeId in if let episodeId = episodeId { self.loadActivityViewWithEpisodeLink(episodeId: episodeId) } else { self.episodeDataNotFoundAlert() } } } else { self.episodeDataNotFoundAlert() } } func episodeDataNotFoundAlert() { let alert = UIAlertController(title: "Not Supported", message: "Data for this episode is unavailable on podverse.fm.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) return } func loadActivityViewWithEpisodeLink(episodeId:String) { let episodeUrlItem = [BASE_URL + "episodes/" + episodeId] let activityVC = UIActivityViewController(activityItems: episodeUrlItem, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = self.view activityVC.completionWithItemsHandler = { activityType, success, items, error in if activityType == UIActivityType.copyToPasteboard { self.showToast(message: kEpisodeLinkCopiedToast) } } self.present(activityVC, animated: true, completion: nil) } func loadActvityViewWithClipLink(mediaRefId:String) { let mediaRefUrlItem = [BASE_URL + "clips/" + mediaRefId] let activityVC = UIActivityViewController(activityItems: mediaRefUrlItem, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = self.view activityVC.completionWithItemsHandler = { activityType, success, items, error in if activityType == UIActivityType.copyToPasteboard { self.showToast(message: kClipLinkCopiedToast) } } self.present(activityVC, animated: true, completion: nil) } @objc func showAboutView() { if let newViewController = self.storyboard?.instantiateViewController(withIdentifier: self.aboutClipsStoryboardId), self.currentChildViewController is ClipsListContainerViewController { newViewController.view.translatesAutoresizingMaskIntoConstraints = false self.cycleFromViewController(oldViewController: self.currentChildViewController!, toViewController: newViewController) self.currentChildViewController = newViewController pageControl.currentPage = 0 } } @objc func showClipsContainerView() { if let newViewController = self.storyboard?.instantiateViewController(withIdentifier: self.clipsListStoryBoardId) as? ClipsListContainerViewController, self.currentChildViewController is AboutPlayingItemViewController { newViewController.view.translatesAutoresizingMaskIntoConstraints = false self.cycleFromViewController(oldViewController: self.currentChildViewController!, toViewController: newViewController) self.currentChildViewController = newViewController newViewController.delegate = self pageControl.currentPage = 1 } } private func addSubview(subView:UIView, toView parentView:UIView) { parentView.addSubview(subView) var viewBindingsDict = [String: AnyObject]() viewBindingsDict["subView"] = subView parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) } private func cycleFromViewController(oldViewController: UIViewController, toViewController newViewController: UIViewController) { oldViewController.willMove(toParentViewController: nil) self.addChildViewController(newViewController) self.addSubview(subView: newViewController.view, toView:self.clipsContainerView) let initialX = newViewController is ClipsListContainerViewController ? self.clipsContainerView.frame.maxX : -self.clipsContainerView.frame.maxX newViewController.view.frame = CGRect(x: initialX, y: 0.0, width: newViewController.view.frame.width, height: newViewController.view.frame.height) UIView.animate(withDuration: 0.5, animations: { if newViewController is ClipsListContainerViewController { oldViewController.view.frame = CGRect(x: -oldViewController.view.frame.width, y: 0.0, width: oldViewController.view.frame.width, height: oldViewController.view.frame.height) } else { oldViewController.view.frame = CGRect(x: oldViewController.view.frame.width, y: 0.0, width: oldViewController.view.frame.width, height: oldViewController.view.frame.height) } newViewController.view.frame = CGRect(x: 0.0, y: 0.0, width: newViewController.view.frame.width, height: newViewController.view.frame.height) }, completion: { finished in oldViewController.view.removeFromSuperview() oldViewController.removeFromParentViewController() newViewController.didMove(toParentViewController: self) }) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Show Add to Playlist" { if let sender = sender as? String, let nowPlayingItem = playerHistoryManager.historyItems.first, let addToPlaylistViewController = segue.destination as? AddToPlaylistViewController { if sender == "Full Episode" { addToPlaylistViewController.shouldSaveFullEpisode = true } else { addToPlaylistViewController.shouldSaveFullEpisode = false } addToPlaylistViewController.playerHistoryItem = nowPlayingItem } } else if segue.identifier == "Show Make Clip Time" { if let nowPlayingItem = playerHistoryManager.historyItems.first, let makeClipTimeViewController = segue.destination as? MakeClipTimeViewController { makeClipTimeViewController.playerHistoryItem = nowPlayingItem makeClipTimeViewController.startTime = Int(self.pvMediaPlayer.progress) } } } @objc fileprivate func setupClipFlags() { self.startTimeLeadingConstraint.constant = 0 self.endTimeLeadingConstraint.constant = 0 let sliderThumbWidthAdjustment:CGFloat = 2.0 if let nowPlayingItem = self.pvMediaPlayer.nowPlayingItem, let startTime = nowPlayingItem.startTime, let endTime = nowPlayingItem.endTime, let dur = self.pvMediaPlayer.duration, dur > 0, nowPlayingItem.isClip() { self.startTimeFlagView.isHidden = false self.endTimeFlagView.isHidden = self.pvMediaPlayer.nowPlayingItem?.endTime == nil // Use UIScreen.main.bounds.width because self.progress.frame.width was giving inconsistent sizes. self.startTimeLeadingConstraint.constant = (CGFloat(Double(startTime) / dur) * UIScreen.main.bounds.width) - sliderThumbWidthAdjustment self.endTimeLeadingConstraint.constant = (CGFloat(Double(endTime) / dur) * UIScreen.main.bounds.width) - sliderThumbWidthAdjustment } else { hideClipData() } } @objc fileprivate func hideClipData() { DispatchQueue.main.async { self.startTimeFlagView.isHidden = true self.endTimeFlagView.isHidden = true } } } extension MediaPlayerViewController:PVMediaPlayerUIDelegate { func playerHistoryItemBuffering() { self.togglePlayIcon() } func playerHistoryItemErrored() { self.togglePlayIcon() } func playerHistoryItemLoaded() { DispatchQueue.main.async { self.setupClipFlags() self.updateTime() self.togglePlayIcon() } } func playerHistoryItemLoadingBegan() { DispatchQueue.main.async { self.startTimeFlagView.isHidden = true self.endTimeFlagView.isHidden = true self.populatePlayerInfo() self.showPendingTime() self.togglePlayIcon() self.setupContainerView() } } func playerHistoryItemPaused() { self.togglePlayIcon() } } extension MediaPlayerViewController:ClipsListDelegate { func didSelectClip(clip: MediaRef) { DispatchQueue.main.async { self.pvMediaPlayer.shouldAutoplayOnce = true let playerHistoryItem = self.playerHistoryManager.convertMediaRefToPlayerHistoryItem(mediaRef: clip) self.pvMediaPlayer.loadPlayerHistoryItem(item: playerHistoryItem) } } }
agpl-3.0
7bc59e7d4c5aac11917750698142acfa
40.844413
227
0.613575
5.49582
false
false
false
false
murphb52/IceAndFireKit
Pod/Classes/Models/IceAndFireObjectParser.swift
1
3180
// // IceAndFireObjectParser.swift // Pods // // Created by Brian Murphy on 21/02/2016. // // import Foundation // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class IceAndFireObjectParser { class func stringFromDictionary(_ dictionary : NSDictionary, key : String) -> String? { if dictionary.object(forKey: key) != nil && dictionary.object(forKey: key) is String { let stringValue = dictionary.object(forKey: key) as? String guard stringValue?.characters.count > 0 else { return nil } return stringValue } return nil } class func integerFromDictionary(_ dictionary : NSDictionary, key : String) -> Int? { if dictionary.object(forKey: key) != nil && dictionary.object(forKey: key) is Int { return dictionary.object(forKey: key) as? Int } return nil } class func dateFromDictionary(_ dictionary : NSDictionary, key : String) -> Date? { if dictionary.object(forKey: key) != nil && dictionary.object(forKey: key) is String { let dateString = dictionary.object(forKey: key) as? String let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone.autoupdatingCurrent dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" return dateFormatter.date(from: dateString!) } return nil } class func arrayFromDictionary<T>(_ dictionary : NSDictionary, key : String!) -> Array<T>? { if dictionary.object(forKey: key) != nil && dictionary.object(forKey: key) is Array<T> { return dictionary.object(forKey: key) as? Array<T> } return nil } class func arrayOfIceAndFireObjectsFromArrayOfUrls<T:IceAndFireObject>(_ urls : [String]?) -> [T]? { guard urls != nil else { return nil } guard urls?.count > 0 else { return nil } var array : [T] = [] for urlString in urls! { let object = T(urlString: urlString) guard object != nil else { continue } array.append(object!) } return array } }
mit
354e34e87b7e8fa412dfdefbe628a3df
25.5
102
0.551887
4.622093
false
false
false
false
omarqazi/HearstKit
Example/HearstKit/LoginViewController.swift
1
2533
// // LoginViewController.swift // SmickChat // // Created by Omar Qazi on 1/30/16. // Copyright © 2016 BQE Software. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class LoginViewController: UIViewController, FBSDKLoginButtonDelegate { var autoAdvanced = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { self.presentingViewController?.dismissViewControllerAnimated(true, completion: { () -> Void in }) if result.isCancelled { print("cancelled") return } print("Declined permisions:",result.declinedPermissions) print("Granted permissions:", result.grantedPermissions) print("Token:",result.token.tokenString) print("User ID",result.token.userID) self.performSegueWithIdentifier("PresentChat", sender: self) } func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool { print("will login") return true } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { print("Did log out") } override func viewDidLoad() { super.viewDidLoad() let loginButton = FBSDKLoginButton() loginButton.center = self.view.center loginButton.readPermissions = ["public_profile","email","user_friends"] loginButton.delegate = self self.view.addSubview(loginButton) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { self.title = "Login With Facebook" if FBSDKAccessToken.currentAccessToken() != nil && !self.autoAdvanced { self.performSegueWithIdentifier("PresentChat", sender: self) self.autoAdvanced = true } } override func viewWillDisappear(animated: Bool) { self.title = "Logout" } /* // 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. } */ }
gpl-3.0
1d43b81a3295e3bf3946ba0d7d688623
30.259259
132
0.661927
5.220619
false
false
false
false
YuanLoveLing/JYPlayer
JYMusicPlayer/JYMusicPlayer/OnlinePlay/JYOnlineMusicListViewController.swift
2
2616
// // JYOnlineMusicListViewController.swift // JYPlayer // // Created by 靳志远 on 2017/3/15. // Copyright © 2017年 靳志远. All rights reserved. // import UIKit fileprivate let JYOnlineMusicListCellId = "JYOnlineMusicListCellId" class JYOnlineMusicListViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // 设置UI setupUI() } /// 设置UI fileprivate func setupUI() { // 设置导航栏 title = "在线音乐列表" // 设置tableView } // MARK: - lazy /// 数据源数据 fileprivate lazy var dataSourceArray: [JYMusic] = { var array = [JYMusic]() for i in 0...2 { var music = JYMusic() music.name = "在线音乐名称\(i)" music.singerName = "在线歌手名称\(i)" if i == 0 { music.urlString = "http://img.owspace.com/F_lbg187532_1475550258.2699715.mp3" }else if i == 1 { music.urlString = "http://img.owspace.com/F_guq226254_1475225218.3955587.mp3" }else if i == 2 { music.urlString = "http://tm3dfds.yusi.tv/uuauth/UUAuth/wymp3/2017/4/4/739287_20174421652_2537_21814_13321681.mp3" } array.append(music) } return array }() } // MARK: - UITableViewDataSource extension JYOnlineMusicListViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSourceArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: JYOnlineMusicListCellId) if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: JYOnlineMusicListCellId) } let music = dataSourceArray[indexPath.row] cell!.textLabel?.text = music.name cell!.detailTextLabel?.text = music.singerName return cell! } } // MARK: - UITableViewDelegate extension JYOnlineMusicListViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let music = dataSourceArray[indexPath.row] // 2、开始现在 JYMusicPlayerView.show(music: music, isOnline: true) } }
apache-2.0
1cf9ab5f069598b5253ce791b2c31a3d
25.557895
130
0.598494
4.342513
false
false
false
false
JGiola/swift-package-manager
Sources/Commands/WatchmanHelper.swift
2
3539
/* This source file is part of the Swift.org open source project Copyright (c) 2018 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import Utility import POSIX import Xcodeproj struct WatchmanMissingDiagnostic: DiagnosticData { static let id = DiagnosticID( type: WatchmanMissingDiagnostic.self, name: "org.swift.diags.watchman-missing", description: { $0 <<< "this feature requires 'watchman' to work" $0 <<< "\n\n installation instructions for 'watchman' are available at https://facebook.github.io/watchman/docs/install.html#buildinstall" } ) } final class WatchmanHelper { /// Name of the watchman-make tool. static let watchmanMakeTool: String = "watchman-make" /// Directory where watchman script should be created. let watchmanScriptsDir: AbsolutePath /// The package root. let packageRoot: AbsolutePath /// The filesystem to operator on. let fs: FileSystem let diagnostics: DiagnosticsEngine init( diagnostics: DiagnosticsEngine, watchmanScriptsDir: AbsolutePath, packageRoot: AbsolutePath, fs: FileSystem = localFileSystem ) { self.watchmanScriptsDir = watchmanScriptsDir self.diagnostics = diagnostics self.packageRoot = packageRoot self.fs = fs } func runXcodeprojWatcher(_ options: XcodeprojOptions) throws { let scriptPath = try createXcodegenScript(options) try run(scriptPath) } func createXcodegenScript(_ options: XcodeprojOptions) throws -> AbsolutePath { let scriptPath = watchmanScriptsDir.appending(component: "gen-xcodeproj.sh") let stream = BufferedOutputByteStream() stream <<< "#!/usr/bin/env bash" <<< "\n\n\n" stream <<< "# Autogenerated by SwiftPM. Do not edit!" <<< "\n\n\n" stream <<< "set -eu" <<< "\n\n" stream <<< "swift package generate-xcodeproj" if let xcconfigOverrides = options.xcconfigOverrides { stream <<< " --xcconfig-overrides " <<< xcconfigOverrides.asString } stream <<< "\n" try fs.createDirectory(scriptPath.parentDirectory, recursive: true) try fs.writeFileContents(scriptPath, bytes: stream.bytes) try fs.chmod(.executable, path: scriptPath) return scriptPath } private func run(_ scriptPath: AbsolutePath) throws { // Construct the arugments. var args = [String]() args += ["--settle", "2"] args += ["-p", "Package.swift", "Package.resolved"] args += ["--run", scriptPath.asString.spm_shellEscaped()] // Find and execute watchman. let watchmanMakeToolPath = try self.watchmanMakeToolPath() print("Starting:", watchmanMakeToolPath.asString, args.joined(separator: " ")) let pathRelativeToWorkingDirectory = watchmanMakeToolPath.relative(to: packageRoot) try exec(path: watchmanMakeToolPath.asString, args: [pathRelativeToWorkingDirectory.asString] + args) } private func watchmanMakeToolPath() throws -> AbsolutePath { if let toolPath = Process.findExecutable(WatchmanHelper.watchmanMakeTool) { return toolPath } diagnostics.emit(data: WatchmanMissingDiagnostic()) throw Diagnostics.fatalError } }
apache-2.0
d80d93c27de2159472b6ab01946c9b4e
33.359223
153
0.667985
4.554698
false
false
false
false
EasySwift/EasySwift
EasySwift_iOS/Core/EZAction.swift
2
11732
// // Action.swift // medical // // Created by zhuchao on 15/4/25. // Copyright (c) 2015年 zhuchao. All rights reserved. // import UIKit import Alamofire import Haneke import Bond import Reachability public var HOST_URL = "" // 服务端域名:端口 public var CODE_KEY = "" // 错误码key,暂不支持路径 如 code public var RIGHT_CODE = 0 // 正确校验码 public var MSG_KEY = "" // 消息提示msg,暂不支持路径 如 msg private var networkReachabilityHandle: UInt8 = 2; open class EZAction: NSObject { // 使用缓存策略 仅首次读取缓存 open class func SEND_IQ_CACHE (_ req: EZRequest) { req.useCache = true req.dataFromCache = req.isFirstRequest self.Send(req) } // 使用缓存策略 优先从缓存读取 open class func SEND_CACHE (_ req: EZRequest) { req.useCache = true req.dataFromCache = true self.Send(req) } // 不使用缓存策略 open class func SEND (_ req: EZRequest) { req.useCache = false req.dataFromCache = false self.Send(req) } open class func Send (_ req: EZRequest) { var url = "" var requestParams = Dictionary<String, AnyObject>() if !req.staticPath.characters.isEmpty { url = req.staticPath } else { if req.scheme.characters.isEmpty { req.scheme = "http" } if req.host.characters.isEmpty { req.host = HOST_URL } url = req.scheme + "://" + req.host + req.path if req.appendPathInfo.characters.isEmpty { requestParams = req.requestParams } else { url = url + req.appendPathInfo } } req.state.value = RequestState.sending req.op = req.manager .request(url, method: req.method, parameters: requestParams, encoding: req.parameterEncoding, headers: nil) // (req.method, url, parameters: requestParams, encoding: req.parameterEncoding) .validate(statusCode: 200 ..< 300) .validate(contentType: req.acceptableContentTypes) .responseJSON { response in // req.response = response if response.result.isFailure { req.error = response.result.error self.failed(req) } else { req.output = response.result.value as! Dictionary<String, AnyObject> self.checkCode(req) } } req.url = req.op?.request!.url self.getCacheJson(req) } open class func Upload (_ req: EZRequest) { var url = "" if !req.staticPath.characters.isEmpty { url = req.staticPath } else { if req.scheme.characters.isEmpty { req.scheme = "http" } if req.host.characters.isEmpty { req.host = HOST_URL } url = req.scheme + "://" + req.host + req.path if req.appendPathInfo.characters.isEmpty { } else { url = url + req.appendPathInfo } } // let urlRequest = urlRequestWithComponents(url, parameters: req.requestParams, images: req.files) // // req.state.value = RequestState.sending // req.op = req.manager // .upload(urlRequest.0.urlRequest, data: urlRequest.1) // .validate(statusCode: 200 ..< 300) // .validate(contentType: req.acceptableContentTypes) // .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in // req.totalBytesWritten = Double(totalBytesWritten) // req.totalBytesExpectedToWrite = Double(totalBytesExpectedToWrite) // req.progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) // }.responseJSON { response in // req.response = response // if response.result.isFailure { // req.error = response.result.error // self.failed(req) // } else { // req.output = response.result.value as! Dictionary<String, AnyObject> // self.checkCode(req) // } // } req.url = req.op?.request!.url } /** 暂时只支持传图片 - parameter urlString: 请求地址 - parameter parameters: 请求参数集合 - parameter images: 图片集合 - returns: (URLRequestConvertible, NSData) */ // fileprivate class func urlRequestWithComponents(_ urlString: String, parameters: Dictionary<String, AnyObject>, images: [(name: String, fileName: String, data: Data)]) -> (URLRequestConvertible, Data) { // // var mutableURLRequest = NSMutableURLRequest(url: URL(string: urlString)!) // mutableURLRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue // let boundaryConstant = "myRandomBoundary12345"; // let contentType = "multipart/form-data;boundary=" + boundaryConstant // mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") // // let uploadData = NSMutableData() // // for img in images { // uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!) // uploadData.append("Content-Disposition: form-data; name=\"\(img.name)\"; filename=\"\(img.fileName)\"\r\n".data(using: String.Encoding.utf8)!) // uploadData.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!) // uploadData.append(img.data) // } // // for (key, value) in parameters { // uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!) // uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!) // } // uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!) // // return (Alamofire.ParameterEncoding.encode(mutableURLRequest, parameters: []).0, uploadData) // } // open class func Download (_ req: EZRequest) { // req.state.value = RequestState.sending // req.op = req.manager // .download(.GET, req.downloadUrl, destination: { (temporaryURL, response) in // let directoryURL = FileManager.default.urls(for: .documentDirectory, // in: .userDomainMask)[0] // return directoryURL.appendingPathComponent(req.targetPath + response.suggestedFilename!) // }) // .validate(statusCode: 200 ..< 300) // .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in // req.totalBytesRead = Double(totalBytesRead) // req.totalBytesExpectedToRead = Double(totalBytesExpectedToRead) // req.progress = Double(totalBytesRead) / Double(totalBytesExpectedToRead) // } // .response { (request, response, _, error) in // if error != nil { // req.error = error // self.failed(req) // } else { // req.state.value = RequestState.success // } // } // req.url = req.op?.request!.url // } fileprivate class func cacheJson (_ req: EZRequest) { if req.useCache { let cache = Shared.JSONCache cache.set(value: .Dictionary(req.output), key: req.cacheKey, formatName: HanekeGlobals.Cache.OriginalFormatName) { JSON in EZPrintln("Cache Success for key: \(req.cacheKey)") } } } fileprivate class func getCacheJson (_ req: EZRequest) { let cache = Shared.JSONCache cache.fetch(key: req.cacheKey).onSuccess { JSON in req.output = JSON.dictionary if req.dataFromCache && !isEmpty(req.output as NSObject) { let delayTime = DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { self.loadFromCache(req) } } } } fileprivate class func loadFromCache (_ req: EZRequest) { if req.needCheckCode && req.state.value != .success { req.codeKey = req.output[CODE_KEY] as? Int if req.codeKey == RIGHT_CODE { req.message = req.output[MSG_KEY] as? String req.state.value = RequestState.successFromCache EZPrintln("Fetch Success from Cache by key: \(req.cacheKey)") } else { req.message = req.output[MSG_KEY] as? String req.state.value = RequestState.errorFromCache EZPrintln(req.message) } } } fileprivate class func checkCode (_ req: EZRequest) { if req.needCheckCode { req.codeKey = req.output[CODE_KEY] as? Int if req.codeKey == RIGHT_CODE { self.success(req) self.cacheJson(req) } else { self.error(req) } } else { req.state.value = RequestState.success self.cacheJson(req) } } fileprivate class func success (_ req: EZRequest) { req.isFirstRequest = false req.message = req.output[MSG_KEY] as? String if req.output.isEmpty { req.state.value = RequestState.error } else { req.state.value = RequestState.success } } fileprivate class func failed (_ req: EZRequest) { req.message = req.error.debugDescription req.state.value = RequestState.failed EZPrintln(req.message) } fileprivate class func error (_ req: EZRequest) { req.message = req.output[MSG_KEY] as? String req.state.value = RequestState.error EZPrintln(req.message) } /* Usage EZAction.networkReachability *->> Bond<NetworkStatus>{ status in switch (status) { case .NotReachable: EZPrintln("NotReachable") case .ReachableViaWiFi: EZPrintln("ReachableViaWiFi") case .ReachableViaWWAN: EZPrintln("ReachableViaWWAN") default: EZPrintln("default") } } */ // open class var networkReachability: Observable<Reachability.NetworkStatus>? { // if let d: AnyObject = objc_getAssociatedObject(self, &networkReachabilityHandle) as AnyObject? { // return d as? Observable<Reachability.NetworkStatus> // } else { // do { // let reachability = try Reachability.NetworkStatus() // let d = Observable<Reachability.NetworkStatus>(reachability.currentReachabilityStatus) // reachability.whenReachable = { reachability in // DispatchQueue.main.async { // d.value = reachability.currentReachabilityStatus // } // } // reachability.whenUnreachable = { reachability in // DispatchQueue.main.async { // d.value = reachability.currentReachabilityStatus // } // } // try reachability.startNotifier() // objc_setAssociatedObject(self, &networkReachabilityHandle, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) // return d // } catch { // print("Unable to create Reachability") // return nil // } // } // } }
apache-2.0
161cafdbe516468e882ecb9b8a1ecc13
36.881967
208
0.568721
4.398173
false
false
false
false
hujiaweibujidao/Gank
Gank/Class/Home/View/AHHomeCell.swift
2
2590
// // AHHomeCell.swift // Gank // // Created by AHuaner on 2016/12/23. // Copyright © 2016年 CoderAhuan. All rights reserved. // import UIKit class AHHomeCell: UITableViewCell { @IBOutlet weak var editorBtn: UIButton! @IBOutlet weak var timeBtn: UIButton! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var separatorLine: UIView! var moreButtonClickedClouse: ((_ indexPath: IndexPath) -> Void)? var indexPath: IndexPath! { didSet { self.separatorLine.isHidden = (indexPath.row == 0) } } var gankModel: AHHomeGankModel! { didSet { contentLabel.text = gankModel.desc! contentLabel.numberOfLines = 0 editorBtn.setTitle(gankModel.user, for: .normal) editorBtn.isHidden = (gankModel.user == nil) ? true : false timeBtn.setTitle(gankModel.publishedAt, for: .normal) moreBrn.frame = gankModel.moreBtnFrame moreBrn.isHidden = !gankModel.isShouldShowMoreButton // cell是否展开 if gankModel.isOpen { self.contentLabel.numberOfLines = 0 self.moreBrn.setTitle("收起", for: .normal) } else { self.contentLabel.numberOfLines = 3 self.moreBrn.setTitle("全文", for: .normal) } } } lazy var moreBrn: UIButton = { let moreBrn = UIButton() moreBrn.setTitle("全文", for: .normal) moreBrn.setTitle("收起", for: .selected) moreBrn.titleLabel?.font = UIFont.systemFont(ofSize: 15) moreBrn.titleLabel?.textAlignment = .left moreBrn.setTitleColor(UIColorMainBlue, for: .normal) self.contentView.addSubview(moreBrn) moreBrn.addTarget(self, action: #selector(moreBtnClicked), for: .touchUpInside) return moreBrn }() func moreBtnClicked () { self.gankModel._cellH = nil if moreButtonClickedClouse != nil { moreButtonClickedClouse!(self.indexPath) } } override func awakeFromNib() { super.awakeFromNib() editorBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0) timeBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } extension AHHomeCell: ViewNameReusable {}
mit
6539edfe23ce5b5ffdad035cc0a0b1c0
28.802326
87
0.591885
4.418966
false
false
false
false
didinozka/DreamsDiary
dreamsDiary/Services/DataManipulation/DataManipulationRemote.swift
1
4100
// // DataManipulationRemote.swift // dreamsDiary // // Created by Dusan Drabik on 08/06/16. // Copyright © 2016 drabik. All rights reserved. // import Foundation import Alamofire import Firebase struct FIRFeedValueData { var description: String = "" var likes: Int = 0 var imageURL: String = "" private var _data: Dictionary<String, AnyObject> = ["description":"", "imgURL": "", "likes": 0] var Data: Dictionary<String, AnyObject>{ return _data } init(description: String, withImageURL: String?, likeCount: Int?){ self.description = description self.likes = likeCount ?? 0 self.imageURL = withImageURL ?? "" let dateTime = NSDate() let formatter = NSDateFormatter() formatter.locale = NSLocale.currentLocale() formatter.dateFormat = "MM-dd-YYYY HH:mm:ss zzz" let nowTimestamp = formatter.stringFromDate(dateTime) _data["description"] = self.description _data["imgURL"] = self.imageURL _data["likes"] = self.likes _data["created"] = nowTimestamp } } class DataManipulationRemote { /** Creates new user in Firebase database with given UID. If UID is nil or "" autogenerate new UID - parameter withUID: Unique Identifier - parameter userData: Data about user in format ["provider": "String:typeOfProvider"] */ static func createNewUser(withUID: String?, userData: Dictionary<String, String>) { let dataRef = k.Firebase.FIR_DATABASE_REF if withUID == "" || withUID == nil { dataRef.child(k.Firebase.FIBDataStorageKeys.USERS).childByAutoId().setValue(userData) NSLog("New user created with autogenerated UID") }else { dataRef.child(k.Firebase.FIBDataStorageKeys.USERS).child(withUID!).setValue(userData) NSLog("New user created with UID") } } /** Create new feed to database and upload image, if is there any. - parameter imageURL: URL to local image, nullable - parameter feedDescription: Description for feed to be created with */ static func createNewFeed(image: UIImage?, feedDescription: String) { let imageData = image == nil ? nil : UIImageJPEGRepresentation(image!, 0.2) uploadImageToFIR(imageData) { (downloadURL: NSURL?) in createFeedOnFIR(feedDescription, imgDwnlURL: downloadURL?.absoluteString) } } /** Creates feed in firebase database */ private static func createFeedOnFIR(feedDescription: String, imgDwnlURL: String?) { let feed = FIRFeedValueData(description: feedDescription, withImageURL: imgDwnlURL, likeCount: nil) k.Firebase.FIR_DATABASE_REF.child(k.Firebase.FIBDataStorageKeys.FEEDS).childByAutoId().setValue(feed.Data) } /** Uploads image from localFileURL URL, if its nil, just call completition closure. - parameter localFileURL: Local URL to image location - parameter completition: With URL for download as NSURL. Completition closure, which is called in both situation, if is image uploaded, or not */ private static func uploadImageToFIR(imageData: NSData?, completition: (NSURL?)->()) { if imageData == nil { completition(nil) return } // let urlComponents = imageData!.absoluteString.componentsSeparatedByString("/") let filename = NSUUID() let imageRef = k.Firebase.FIR_STORAGE_REF.child("image/\(filename)") let _ = imageRef.putData(imageData!, metadata: nil) { (meta: FIRStorageMetadata?, err: NSError?) in if err != nil { print("Error occured during uploading '\(filename)' image.") return } let uploadedImageDownloadURL = meta?.downloadURL() completition(uploadedImageDownloadURL) } } }
gpl-3.0
070857fed76fa8432a77f314fbc283c4
30.775194
148
0.617468
4.760743
false
false
false
false
magicien/GLTFSceneKit
Sources/GLTFSceneKit/GLTFSceneKit+BundleFinder.swift
1
2526
// // GLTFSceneKit+BundleFinder.swift // // // Created by Andrew Breckenridge on 9/6/21. // /// required to enable Swift previews in Xcode 12: https://github.com/pointfreeco/isowords/discussions/104 import Foundation #if !DEBUG extension Bundle { static var module_workaround: Bundle = { #if SWIFT_PACKAGE return .module #else return Bundle(for: GLTFUnarchiver.self) #endif }() } #else private let moduleName = "GLTFSceneKit_GLTFSceneKit" extension Foundation.Bundle { static var module_workaround: Bundle = { #if !SWIFT_PACKAGE return Bundle(for: GLTFUnarchiver.self) #else /* The name of your local package, prepended by "LocalPackages_" for iOS and "PackageName_" for macOS. You may have same PackageName and TargetName*/ let bundleNameIOS = "LocalPackages_\(moduleName)" let bundleNameMacOs = "PackageName_\(moduleName)" let andrewSBBundleName = moduleName let candidates = [ /* Bundle should be present here when the package is linked into an App. */ Bundle.main.resourceURL, /* Bundle should be present here when the package is linked into a framework. */ Bundle(for: GLTFUnarchiver.self).resourceURL, /* For command-line tools. */ Bundle.main.bundleURL, // AndrewSB reverse engineered this one Bundle(for: GLTFUnarchiver.self).resourceURL?.appendingPathComponent("Bundle").appendingPathComponent("Application"), /* Bundle should be present here when running previews from a different package (this is the path to "…/Debug-iphonesimulator/"). */ Bundle(for: GLTFUnarchiver.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent(), Bundle(for: GLTFUnarchiver.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent(), ] for candidate in candidates { let bundlePathiOS = candidate?.appendingPathComponent(bundleNameIOS + ".bundle") let bundlePathMacOS = candidate?.appendingPathComponent(bundleNameMacOs + ".bundle") let andrewSBBundlePath = candidate?.appendingPathComponent(andrewSBBundleName + ".bundle") if let bundle = bundlePathiOS.flatMap(Bundle.init(url:)) { return bundle } else if let bundle = bundlePathMacOS.flatMap(Bundle.init(url:)) { return bundle } else if let bundle = andrewSBBundlePath.flatMap(Bundle.init(url:)) { return bundle } } fatalError("unable to find bundle") #endif }() } #endif
mit
4470a7f5a787c6d65ddee010e3b2c7ae
36.117647
153
0.704834
4.631193
false
false
false
false
wtrumler/FluentSwiftAssertions
FluentSwiftAssertions/ContiguousArrayExtension.swift
1
1608
// // ContiguousArrayExtension.swift // FluentSwiftAssertions // // Created by Wolfgang Trumler on 13.05.17. // Copyright © 2017 Wolfgang Trumler. All rights reserved. // import Foundation import XCTest extension ContiguousArray where Element: Equatable { public var should : ContiguousArray { return self } public func beEqualTo( _ expression2: @autoclosure () throws -> ContiguousArray<Element>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> ContiguousArray<Element>, _ exp2: @autoclosure () throws -> ContiguousArray<Element>, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertEqual) { assertionFunction(self, expression2, message, file, line) } public func notBeEqualTo( _ expression2: @autoclosure () throws -> ContiguousArray<Element>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> ContiguousArray<Element>, _ exp2: @autoclosure () throws -> ContiguousArray<Element>, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotEqual) { assertionFunction(self, expression2, message, file, line) } }
mit
8084852f741262e3a2d253cde5191572
46.264706
285
0.58743
5.117834
false
false
false
false
colourful987/JustMakeGame-FlappyBird
Code/L02/FlappyBird-Start/FlappyBird/GameScene.swift
2
1525
// // GameScene.swift // FlappyBird // // Created by pmst on 15/10/4. // Copyright (c) 2015年 pmst. All rights reserved. // import SpriteKit enum Layer: CGFloat { case Background case Foreground case Player } class GameScene: SKScene { let worldNode = SKNode() var playableStart:CGFloat = 0 var playableHeight:CGFloat = 0 override func didMoveToView(view: SKView) { addChild(worldNode) setupBackground() setupForeground() } // MARK: Setup Method func setupBackground(){ // 1 let background = SKSpriteNode(imageNamed: "Background") background.anchorPoint = CGPointMake(0.5, 1) background.position = CGPointMake(size.width/2.0, size.height) background.zPosition = Layer.Background.rawValue worldNode.addChild(background) // 2 playableStart = size.height - background.size.height playableHeight = background.size.height } func setupForeground() { let foreground = SKSpriteNode(imageNamed: "Ground") foreground.anchorPoint = CGPoint(x: 0, y: 1) foreground.position = CGPoint(x: 0, y: playableStart) foreground.zPosition = Layer.Foreground.rawValue worldNode.addChild(foreground) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
3d988e4c5861283ea1a520f1f35646b0
24.813559
82
0.636244
4.532738
false
false
false
false
DopamineLabs/DopamineKit-iOS
BoundlessKit/Classes/BoundlessKit.swift
1
3311
// // BoundlessKit.swift // BoundlessKit // // Created by Akash Desai on 4/7/16. // Copyright © 2018 Boundless Mind. All rights reserved. // import Foundation open class BoundlessKit : NSObject { internal static var _shared: BoundlessKit? @objc open class var shared: BoundlessKit { guard _shared == nil else { return _shared! } _shared = BoundlessKit() return _shared! } internal let apiClient: BoundlessAPIClient internal init(apiClient: BoundlessAPIClient) { self.apiClient = apiClient super.init() } internal override convenience init() { guard let properties = BoundlessProperties.fromFile(using: BKUserDefaults.standard) else { fatalError("Missing <BoundlessProperties.plist> file") } self.init(apiClient: BoundlessAPIClient(properties: properties)) } @objc open func track(actionID: String, metadata: [String: Any]) { let action = BKAction(actionID, metadata) apiClient.commit(action) apiClient.synchronize() } @objc open func reinforce(actionID: String, metadata: [String: Any], completion: @escaping (String)->Void) { let decision = apiClient.remove(decisionFor: actionID) let reinforcement = BKReinforcement(decision, metadata) DispatchQueue.main.async { completion(reinforcement.name) } apiClient.commit(reinforcement) apiClient.synchronize() } } extension BoundlessKit { @objc open func track(actionID: String) { track(actionID: actionID, metadata: [:]) } @objc open func reinforce(actionID: String, completion: @escaping (String)->Void) { reinforce(actionID: actionID, metadata: [:], completion: completion) } } extension BoundlessKit { /// Set a custom identity for Boundless /// /// - Parameters: /// - id: A non-empty string that is less than 36 characters, containing only alphanumerics and dashes. If an invalid string is passed, one will be genereated using the UUID class. /// - completion: An optional callback taking the most recent user id and user's experiment group @objc open func setCustomUserId(_ id: String?, completion: ((String?, String?) -> ())? = nil) { apiClient.set(customUserIdentifier: id, completion: completion) } /// Get the user identifier used within the Boundless environment. /// /// You can change the identifier source in `BoundlessProperties.plist`. Set the key `userIdSource` to `idfv`, `idfa`, `generateUUID` or `custom`. /// - idfv: Identifier for vendor /// - idfa: Identifier for advertiser /// - default: Identifier generated by UUID class /// - custom: Identifier that is manually set /// /// - Returns: /// The identifier string, or nil if one has not been. /// An identifier is not set automatically if `userIdSource` is set to `custom`, and BoundlessKit.shared.setCustomUserId() has not yet been called. @objc open func getUserId() -> String? { return apiClient.credentials.user.id } @objc open func getUserExperimentGroup() -> String? { return apiClient.credentials.user.experimentGroup } }
mit
a7c5f288353b2e3bab2344ddeca9fe84
32.434343
186
0.649849
4.497283
false
false
false
false
DarlingXIe/WeiBoProject
WeiBo/WeiBo/Classes/View/compose/未命名文件夹 2/XDLComposeView.swift
2
7156
// // XDLComposeView.swift // WeiBo // // Created by DalinXie on 16/9/28. // Copyright © 2016年 itcast. All rights reserved. // /* hints: 1. create UIButtonClass to setupUI with imageView and label. recall the funcation with layout subviews to layout subviews setting its frame 2. composeView add the screenSnap and titleLabel and import the snapScreen.h to make image from snap */ import UIKit import pop class XDLComposeView: UIView { //define the controller from outside var target : UIViewController? // define the array with button lazy var buttons :[UIButton] = {()-> [UIButton] in let button = [UIButton]() //label.textColor = UIcolor.red return button }() var infoArray: NSArray? override init(frame: CGRect){ super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - setupUI private func setupUI(){ //backgroundColor = UIColor.black frame.size = UIScreen.main.bounds.size addSubview(bgImage) addSubview(logoLabel) bgImage.snp_makeConstraints { (make) in make.edges.equalTo(self) } logoLabel.snp_makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self).offset(200) } addChildButton() } //MARK: - func addChildButtons() func addChildButton(){ // the width of button itemW: // the height of button itemH: let itemW:CGFloat = 80 let itemH:CGFloat = 110 //cal the margin for eachbuttons let itemMargin = (XDLScreenW - 3 * itemW)/4 //information from list for buttonPicture and title let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)! //array from plist let array = NSArray(contentsOfFile: path)! self.infoArray = array for i in 0..<array.count{ //create Button let button = XDLComposeButton(textColor: UIColor.darkGray, fontSize: 14) button.addTarget(self, action: #selector(childButtonClick(button:)), for: .touchUpInside) //info about picture and tilte let dict = array[i]as![String : String] //buttoninfor with image and title from the dict button.setImage(UIImage(named:dict["icon"]!), for: .normal) //button.setImage(UIImage(named: "tabbar_compose_weibo"), for: UIControlState.normal) button.setTitle(dict["title"], for: .normal) //add width and height for buttons button.frame.size = CGSize(width: itemW, height: itemH) //col two tows and three cols let col = i % 3 let row = i / 3 let x = CGFloat(col) * itemW + CGFloat(col + 1) * itemMargin let y = CGFloat(row) * itemH + XDLScreenH button.frame.origin = CGPoint(x: x, y: y) addSubview(button) buttons.append(button) } } //MARK: - to show this XDLComposeView func show(target: UIViewController){ self.target = target //let window = UIApplication.shared.keyWindow //window?.addSubview(self) self.target?.view.addSubview(self) for(index,value) in buttons.enumerated(){ buttonAnimation(index: index, button: value, isPullUp: true) } } //MARK: - setting the buttons animation func buttonAnimation(index: Int, button: UIButton, isPullUp:Bool){ let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter) anim?.toValue = NSValue.init(cgPoint: CGPoint(x: button.center.x, y: button.center.y + (isPullUp ? -300 : 300))) anim?.springBounciness = 12 anim?.springSpeed = 10 if isPullUp{ anim?.beginTime = CACurrentMediaTime() + Double(index)*0.25 }else{ anim?.beginTime = CACurrentMediaTime() } button.pop_add(anim, forKey: nil) } //MARK: - click screen to remove view override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for (index, button) in buttons.reversed().enumerated(){ buttonAnimation(index: index, button: button, isPullUp: false) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { self.removeFromSuperview() } } //MARK: - clickButton @objc private func childButtonClick(button:UIButton){ UIView.animate(withDuration: 1, animations: { for value in self.buttons{ if button == value{ value.transform = CGAffineTransform.init(scaleX: 2, y: 2) }else{ value.transform = CGAffineTransform.init(scaleX: 0.2, y: 0.2) } value.alpha = 0.1 } }) { (_) in print("-----controller") let index = self.buttons.index(of: button) ?? 0 let dict = self.infoArray![index] as![String : String] if let name = dict["class"]{ //let result = NSStringFromClass(XDLComposeViewController.self) let type = NSClassFromString(name)! as! UIViewController.Type let vc = type.init() self.target?.present(XDLNavigationViewController(rootViewController: vc), animated: true, completion: { self.removeFromSuperview() }) } } } //MARK: - lazy var to create the UI private lazy var bgImage :UIImageView = {()-> UIImageView in let imageView = UIImageView(image: UIImage.getScreenSnap()?.applyLightEffect()) return imageView }() private lazy var logoLabel :UIImageView = {()-> UIImageView in let imageView = UIImageView(image: UIImage(named: "compose_slogan")) return imageView }() //MARK: - make screenSnap private func getScreenSnap() -> UIImage?{ //capture the window let window = UIApplication.shared.keyWindow //beginImageContext with window size UIGraphicsBeginImageContextWithOptions(window!.bounds.size, false, 0) //draw context with window with beginImageContextSize window?.drawHierarchy(in: window!.bounds, afterScreenUpdates: false) //capture the image from the windowContext let image = UIGraphicsGetImageFromCurrentImageContext() //end context UIGraphicsEndImageContext() //reture image return image } }
mit
d0ed3857abd42dfaab65cb41ffbf21d7
29.699571
151
0.559066
5.016129
false
false
false
false
dehesa/apple-utilites
Tests/commonTests/swiftTests/HexadecimalTests.swift
2
1247
import XCTest @testable import Utils /// Tests the hexadecimal functionality class HexadecimalTests: XCTestCase { static var allTests = [ ("testHexadecimalStrings", testHexadecimalStrings), ("testHexadecimalConversion", testHexadecimalConversion) ] /// Tests the `String` add-ons. func testHexadecimalStrings() { let bigNumbers = ["#202020", "0x202020", "0X202020", "#0x202020", "202020"] let resultBig = bigNumbers.map { $0.dropHexadecimalPrefix() } XCTAssertTrue(resultBig.filter{ $0.characters.count != 6 }.isEmpty) let smallNumbers = ["#222", "0x222", "0X222", "#0x222", "222"] let resultSmall = smallNumbers.map { $0.dropHexadecimalPrefix() } XCTAssertTrue(resultSmall.filter{ $0.characters.count != 3 }.isEmpty) } /// Tests the `Int` add-ons. func testHexadecimalConversion() { let hexadecimals = ["#000000", "0xFFFFFF", "0X202020", "#0x888888", "A2B7F3", "0", "B45"] do { let _ = try hexadecimals.map { try Int(hexString: $0) } let _ = try hexadecimals.map { try UInt(hexString: $0) } } catch let error { XCTFail(error.localizedDescription) } } }
mit
a589d3580985452da4184eed90ed6182
36.787879
97
0.611868
3.909091
false
true
false
false
SoneeJohn/WWDC
ConfCore/TranscriptIndexer.swift
1
6094
// // TranscriptIndexer.swift // WWDC // // Created by Guilherme Rambo on 27/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import RealmSwift import SwiftyJSON extension Notification.Name { public static let TranscriptIndexingDidStart = Notification.Name("io.wwdc.app.TranscriptIndexingDidStartNotification") public static let TranscriptIndexingDidStop = Notification.Name("io.wwdc.app.TranscriptIndexingDidStopNotification") } public final class TranscriptIndexer: NSObject { private let storage: Storage public init(_ storage: Storage) { self.storage = storage super.init() } /// The progress when the transcripts are being downloaded/indexed public var transcriptIndexingProgress: Progress? private let asciiWWDCURL = "http://asciiwwdc.com/" fileprivate let bgThread = DispatchQueue.global(qos: .utility) fileprivate lazy var backgroundOperationQueue: OperationQueue = { let q = OperationQueue() q.underlyingQueue = self.bgThread q.name = "Transcript Indexing" return q }() public static let minTranscriptableSessionLimit: Int = 20 // TODO: increase 2017 to 2018 when transcripts for 2017 become available public static let transcriptableSessionsPredicate: NSPredicate = NSPredicate(format: "year > 2012 AND year < 2017 AND transcriptIdentifier == '' AND SUBQUERY(assets, $asset, $asset.rawAssetType == %@).@count > 0", SessionAssetType.streamingVideo.rawValue) public static func needsUpdate(in storage: Storage) -> Bool { let transcriptedSessions = storage.realm.objects(Session.self).filter(TranscriptIndexer.transcriptableSessionsPredicate) return transcriptedSessions.count > minTranscriptableSessionLimit } /// Try to download transcripts for sessions that don't have transcripts yet public func downloadTranscriptsIfNeeded() { let transcriptedSessions = storage.realm.objects(Session.self).filter(TranscriptIndexer.transcriptableSessionsPredicate) let sessionKeys: [String] = transcriptedSessions.map({ $0.identifier }) indexTranscriptsForSessionsWithKeys(sessionKeys) } func indexTranscriptsForSessionsWithKeys(_ sessionKeys: [String]) { // ignore very low session counts guard sessionKeys.count > TranscriptIndexer.minTranscriptableSessionLimit else { waitAndExit() return } transcriptIndexingProgress = Progress(totalUnitCount: Int64(sessionKeys.count)) for key in sessionKeys { guard let session = storage.realm.object(ofType: Session.self, forPrimaryKey: key) else { return } guard session.transcriptIdentifier.isEmpty else { continue } indexTranscript(for: session.number, in: session.year, primaryKey: key) } } fileprivate var batch: [Transcript] = [] { didSet { if batch.count >= 20 { store(batch) storage.storageQueue.waitUntilAllOperationsAreFinished() batch.removeAll() } } } fileprivate func store(_ transcripts: [Transcript]) { storage.backgroundUpdate { backgroundRealm in transcripts.forEach { transcript in guard let session = backgroundRealm.object(ofType: Session.self, forPrimaryKey: transcript.identifier) else { NSLog("Session not found for \(transcript.identifier)") return } session.transcriptIdentifier = transcript.identifier session.transcriptText = transcript.fullText backgroundRealm.add(transcript, update: true) } } } fileprivate func indexTranscript(for sessionNumber: String, in year: Int, primaryKey: String) { guard let url = URL(string: "\(asciiWWDCURL)\(year)//sessions/\(sessionNumber)") else { return } var request = URLRequest(url: url) request.setValue("application/json", forHTTPHeaderField: "Accept") let task = URLSession.shared.dataTask(with: request) { [unowned self] data, response, error in defer { self.transcriptIndexingProgress?.completedUnitCount += 1 self.checkForCompletion() } guard let jsonData = data else { NSLog("No data returned from ASCIIWWDC for \(primaryKey)") return } let result = TranscriptsJSONAdapter().adapt(JSON(data: jsonData)) guard case .success(let transcript) = result else { NSLog("Error parsing transcript for \(primaryKey)") return } self.storage.storageQueue.waitUntilAllOperationsAreFinished() self.batch.append(transcript) } task.resume() } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == #keyPath(OperationQueue.operationCount) { NSLog("operationCount = \(backgroundOperationQueue.operationCount)") } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } private func checkForCompletion() { guard let progress = transcriptIndexingProgress else { return } #if DEBUG NSLog("Completed: \(progress.completedUnitCount) Total: \(progress.totalUnitCount)") #endif if progress.completedUnitCount >= progress.totalUnitCount { DispatchQueue.main.async { #if DEBUG NSLog("Transcript indexing finished") #endif self.storage.storageQueue.waitUntilAllOperationsAreFinished() self.waitAndExit() } } } fileprivate func waitAndExit() { DispatchQueue.main.asyncAfter(deadline: .now() + 5) { exit(0) } } }
bsd-2-clause
12f2c435bea72fcf5ffbc759ae22d266
34.017241
259
0.650254
5.252586
false
false
false
false
Drakken-Engine/GameEngine
DrakkenEngine/dScene.swift
1
3740
// // dScene.swift // DrakkenEngine // // Created by Allison Lindner on 26/08/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import Foundation import simd public class dScene { public var size: float2 = float2(1920.0, 1080.0) public var scale: Float = 1.0 internal var time: dTime = dTime() internal var name: String = "scene" internal var root: dTransform = dTransform(name: "root") internal var DEBUG_MODE = false internal var simpleRender: dSimpleSceneRender? public init() { root._scene = self } public func add(transform: dTransform) { if transform._scene == nil { transform.set(scene: self) } root.add(child: transform) } public func remove(transform: dTransform) { root.remove(child: transform) } internal func load(url: URL) { var fileString: String = "" do { fileString = try String(contentsOf: url) load(json: fileString) } catch { NSLog("Scene file error") } } internal func load(jsonFile: String) { if let url = dCore.instance.SCENES_PATH?.appendingPathComponent(jsonFile).appendingPathExtension("dkscene") { self.load(url: url) } } internal func load(data: Data) { self.clear() self.root._scene = self let json = JSON(data: data) self.name = json["name"].stringValue print("----------------------------------------------") print("name: \(name)") print("----------------------------------------------") print("----------------- SETUP --------------------") print("----------------------------------------------") let transforms = json["transforms"].arrayValue for t in transforms { let transform = dTransform(json: t) self.add(transform: transform) } } private func load(json: String) { if let dataFromString = json.data(using: String.Encoding.utf8) { self.load(data: dataFromString) } } internal func toData() -> Data? { var jsonDict = [String: JSON]() jsonDict["name"] = JSON(self.name) var transformsArray: [JSON] = [] for t in self.root.childrenTransforms { transformsArray.append(JSON(t.value.toDict())) } jsonDict["transforms"] = JSON(transformsArray) let json = JSON(jsonDict) do { let data = try json.rawData(options: JSONSerialization.WritingOptions.prettyPrinted) let string = String(data: data, encoding: String.Encoding.utf8) NSLog(string!) return data } catch let error { NSLog("JSON conversion FAIL!! \(error)") } return nil } internal func toJSON() -> JSON? { var jsonDict = [String: JSON]() jsonDict["name"] = JSON(self.name) jsonDict["setup"] = JSON(DrakkenEngine.toDict()) var transformsArray: [JSON] = [] for t in self.root.childrenTransforms { transformsArray.append(JSON(t.value.toDict())) } jsonDict["transforms"] = JSON(transformsArray) let json = JSON(jsonDict) return json } internal func clear() { self.root.removeAll() } internal func sendMessageToAll(_ message: NSString) { if simpleRender != nil { simpleRender!.sendMessage(message) } } }
gpl-3.0
64965bc35c3f71aee5dd2873dea5878e
25.707143
117
0.512169
4.72096
false
false
false
false
orlandoamorim/GoBus
GoBus/Classes/DataTypes.swift
1
3369
// // DataTypes.swift // GoBus ( https://github.com/orlandoamorim/GoBus ) // // Created by Orlando Amorim on 23/05/16. // Copyright © 2016 Orlando Amorim. All rights reserved. // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreLocation import UIKit ///Used in GoBus.getBus(_:) to continuously update the request public protocol GoBusDelegate { func getBus(bus:[Bus]?, lines: [Line]?,error: NSError?) } /** Inthegra API request options. ```` case Linhas case BuscaLinha case Paradas case ParadasBusca case ParadasLinhaBusca case Veiculos case VeiculosLinhaBusca ```` */ public enum GoBusGetTypes:String { case Linhas = "linhas" case BuscaLinha = "linhas?busca=" case Paradas = "paradas" case ParadasBusca = "paradas?busca=" case ParadasLinhaBusca = "paradasLinha?busca=" case Veiculos = "veiculos" case VeiculosLinhaBusca = "veiculosLinha?busca=" } extension NSDate { func dateFormatter() -> NSDateFormatter { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle dateFormatter.locale = NSLocale(localeIdentifier: "en_US") dateFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss 'GMT'" return dateFormatter } func minutesFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.Minute, fromDate: date, toDate: self, options: []).minute } } extension CLLocationCoordinate2D { func distanceInMetersFrom(otherCoord : CLLocationCoordinate2D) -> CLLocationDistance { let firstLoc = CLLocation(latitude: self.latitude, longitude: self.longitude) let secondLoc = CLLocation(latitude: otherCoord.latitude, longitude: otherCoord.longitude) return firstLoc.distanceFromLocation(secondLoc) } ///If the CLLocationCoordinate2D has latitude and longitude equals to 0.0 returns true func isZero() -> Bool { if self.longitude == 0.0 && self.latitude == 0.0 { return true } return false } } //http://stackoverflow.com/a/34537466/4642682 extension Array where Element: AnyObject { mutating func remove(object: Element) { if let index = indexOf({ $0 === object }) { removeAtIndex(index) } } }
mit
af28d0446f4122a67ad37ffdaf41c1bb
33.020202
113
0.702494
4.102314
false
false
false
false
daniel-barros/TV-Calendar
TV Calendar/AlertPresenter.swift
1
14265
// // AlertPresenter.swift // TV Calendar // // Created by Daniel Barros López on 2/13/17. // Copyright © 2017 Daniel Barros. All rights reserved. // import ExtendedUIKit import TemporaryAlert /// Shows temporary alerts and action sheets for multiple purposes. /// - warning: Always use the `AlertPresenter` from the presentation controller itself, or really make sure that the presentation controller still exists when you show alerts, since the `AlertPresenter` holds an unowned reference to it. class AlertPresenter { /// The view controller which will be presenting action sheets. unowned let presentationController: UIViewController fileprivate var loadingView: LoadingView? init(presentationController: UIViewController) { self.presentationController = presentationController } } /// MARK: - Show Tracking Alerts extension AlertPresenter { // TODO: Handle ShowTracker errors, like persistence or calendar /// Shows a temporary alert indicating the success/failure of the operation. func showDidTrackAlert(for show: Show, withSuccess success: Bool, addedCalendarEvents: Bool, error: Error?) { if success { let numberOfEvents = self.numberOfEvents(for: show) let message: String? if addedCalendarEvents { if numberOfEvents == 0 { message = nil } else if numberOfEvents == 1 { message = "1 event added to your calendar" } else { message = "\(numberOfEvents) events added to your calendar" } } else { message = nil } TemporaryAlert.show(image: .checkmark, title: "Added to Tracked Shows", message: message) } else { let title, message: String guard let error = error as? Show.FetchError? else { assertionFailure("Case not handled"); return } switch error { case .noConnection?: title = "Error: " + error!.description message = "Retry when internet connection is available" case .serverFailure?: title = "Error: " + error!.description message = "Retry in a few minutes" case .persistenceFailure?: title = "Error: " + error!.description message = "Try again later" case .unknown?, nil: title = "Error" message = "Couldn't track the show" } TemporaryAlert.show(image: .cross, title: title, message: message) } } /// Shows an action sheet asking the user for confirmation. func showStopTrackingConfirmationAlert(for show: Show, completion: @escaping (Bool) -> ()) { let numberOfEvents = self.numberOfEvents(for: show) let message: String? if numberOfEvents == 0 { message = nil } else if numberOfEvents == 1 { message = "1 event will be removed from your calendar" } else { message = "\(numberOfEvents) events will be removed from your calendar" } let actions = [cancelAction(completion), affirmativeAction(title: "Stop Tracking", style: .destructive, completion)] presentActionSheet(title: "Stop Tracking \"" + show.title + "\"", message: message, actions: actions) } // TODO: Handle ShowTracker errors, like persistence or calendar /// Shows a temporary alert showing an error explanation. func showStopTrackingErrorAlert(for show: Show) { TemporaryAlert.show(image: .cross, title: "Error", message: "Try again later") } } // MARK: - Calendar Settings Updates Confirmation extension AlertPresenter { /// Shows an alert sheet warning that calendar events will be removed, giving the user an option to keep those events. func showRemoveCalendarEventsConfirmationAlert(numberOfAffectedEvents: Int?, completion: @escaping (_ confirmed: Bool, _ keepingExistingEvents: Bool) -> ()) { let numberOfEvents = numberOfAffectedEvents == nil ? "Several" : "\(numberOfAffectedEvents!)" let eventOrEvents = numberOfAffectedEvents == nil || numberOfAffectedEvents! > 1 ? "Events" : "Event" let actions = [cancelAction(completion), affirmativeAction(title: "Continue and Keep Events", secondChoice: true, completion), affirmativeAction(title: "Continue and Remove Events", secondChoice: false, style: .destructive, completion)] presentActionSheet(title: "This Will Remove \(numberOfEvents) \(eventOrEvents) from Your Calendar", message: "Do you want to keep those events?", actions: actions) } func showUseLocalCalendarConfirmationAlert(newValue: Bool, completion: @escaping (_ confirmed: Bool) -> ()) { let title = newValue ? "Local Calendar" : "iCloud Calendar" let message = newValue ? "Your Shows calendar will be rebuilt as a local calendar.\n It won't sync with your other devices." : "Your Shows calendar will be rebuilt as an iCloud calendar, if available.\n It will sync with other devices with iCloud Calendars enabled." let actions = [cancelAction(completion), affirmativeAction(title: newValue ? "Use Local Calendar" : "Use iCloud Calendar", style: .destructive, completion)] presentActionSheet(title: title, message: message, actions: actions) } /// Shows an alert asking confirmation for resetting a show to the default calendar settings, giving an option to reset all shows. func showResetToDefaultSettingsConfirmationAlert(completion: @escaping (_ confirmed: Bool, _ resetAllShows: Bool) -> ()) { let actions = [cancelAction(completion), affirmativeAction(title: "Reset all Shows", secondChoice: true, completion), affirmativeAction(title: "Reset this Show", secondChoice: false, completion)] presentActionSheet(title: "Reset to Default Settings", message: "Do you want to reset all shows to the default settings?", actions: actions) } func showDisableCreationOfEventsForAllSeasonsConfirmationAlert(completion: @escaping (_ confirmed: Bool) -> ()) { let actions = [cancelAction(completion), affirmativeAction(title: "Disable Setting", completion)] presentActionSheet(title: "Disable Create Events for all Seasons", message: "Existing events from past seasons won't be affected.", actions: actions) } } // MARK: - Calendar Settings Updates Errors extension AlertPresenter { func showCalendarSettingsUpdateErrorAlert(with error: CalendarSettingsManager.UpdateError?) { switch error { case .calendarFailure?: TemporaryAlert.show(image: .cross, title: "Error", message: "We had a problem accessing your calendar. Events might not have been updated properly.") case .persistenceFailure?, nil: TemporaryAlert.show(image: .cross, title: "Error", message: "Try again later.") case .userCancellation?: break } } } // MARK: - Calendar Events Activation Controller extension AlertPresenter { /// Present a view controller showing information about calendar events creation and giving the option to enable or disable calendar events. func showCalendarEventsActivationController(completion: @escaping (Bool) -> ()) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: String(describing: AppFeatureActivationViewController.self)) as! AppFeatureActivationViewController vc.configure(for: .calendarEvents(completion: completion)) presentationController.present(vc, animated: true, completion: nil) } } // MARK: - Unlock Unlimited Tracking Controller extension AlertPresenter { /// Present a view controller showing information about unlocking unlimited tracking and giving the option to purchase this IAP or cancel. func showUnlimitedTrackingActivationController(completion: @escaping (AppFeatureActivationViewController.Feature.UnlockUnlimitedTrackingOption) -> ()) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: String(describing: AppFeatureActivationViewController.self)) as! AppFeatureActivationViewController vc.configure(for: .unlockUnlimitedTracking(completion: completion)) presentationController.present(vc, animated: true, completion: nil) } } // MARK: - Loading Indicator extension AlertPresenter { func showLoadingIndicator(text: String?) { let overlay = LoadingView() overlay.label.text = text loadingView = overlay overlay.frame = presentationController.view.bounds overlay.autoresizingMask = [.flexibleWidth, .flexibleHeight] presentationController.view.addSubview(overlay) presentationController.view.bringSubview(toFront: overlay) overlay.fadeIn() } func stopLoadingIndicator() { guard let overlay = loadingView else { return } loadingView = nil overlay.fadeOut(completion: { overlay.removeFromSuperview() }) } } // MARK: - Quick "Create Calendar Events" Setting Change Warning extension AlertPresenter { func showReenablingCreateCalendarEventsWarning(completion: @escaping (Bool) -> ()) { let alert = UIAlertController(title: "Warning", message: "Disabling and enabling calendar events so quickly might lead to duplicate events, due to how iCloud calendars sync works.\n Are you sure you want to continue?", preferredStyle: .alert) alert.addAction(cancelAction(completion)) alert.addAction(affirmativeAction(title: "Enable Events", completion)) self.presentationController.present(alert, animated: true, completion: nil) } } // MARK: - In-App Purchase Errors extension AlertPresenter { func showTrackingLimitIAPErrorAlert(with error: InAppPurchaseManager.IAPError?) { let message: String switch error! { case .iTunesStoreConnectionFailure: message = "Failed to connect to the iTunes Store." case .userCantMakePayments: message = "The user is not allowed to make payments due to account restrictions." case .productUnavailable, .purchaseFailure(_), .other(_): message = "The purchase could not be completed. Please try again later." } TemporaryAlert.show(image: .cross, title: "Purchase Error", message: message) } } // MARK: - Helpers fileprivate extension AlertPresenter { func numberOfEvents(for show: Show) -> Int { return CalendarEventsManager.authorizationStatus == .authorized ? CalendarEventsManager.numberOfEvents(for: show) : 0 } // Creates an UIAlertController with .actionSheet style and the specified title and message, adds the specified actions to it, and presents it using the `presentationController`. func presentActionSheet(title: String, message: String?, actions: [UIAlertAction]) { let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) for action in actions { actionSheet.addAction(action) } self.presentationController.present(actionSheet, animated: true, completion: nil) } /// Calls the completion passing `false`. func cancelAction(_ completion: @escaping (Bool) -> ()) -> UIAlertAction { return UIAlertAction(title: "Cancel", style: .cancel, handler: { action in self.presentationController.dismiss(animated: true, completion: nil) completion(false) }) } /// Calls the completion passing `false`, `false`. func cancelAction(secondChoice: Bool = false, _ completion: @escaping (Bool, Bool) -> ()) -> UIAlertAction { return UIAlertAction(title: "Cancel", style: .cancel, handler: { action in self.presentationController.dismiss(animated: true, completion: nil) completion(false, secondChoice) }) } // Calls the completion passing `true`. func affirmativeAction(title: String, style: UIAlertActionStyle = .default, _ completion: @escaping (Bool) -> ()) -> UIAlertAction { return UIAlertAction(title: title, style: style, handler: { action in self.presentationController.dismiss(animated: true, completion: nil) completion(true) }) } // Calls the completion passing `true` for the first parameter, and `secondChoice` for the second one. func affirmativeAction(title: String, secondChoice: Bool, style: UIAlertActionStyle = .default, _ completion: @escaping (Bool, Bool) -> ()) -> UIAlertAction { return UIAlertAction(title: title, style: style, handler: { action in self.presentationController.dismiss(animated: true, completion: nil) completion(true, secondChoice) }) } }
gpl-3.0
4a6507b4f56d76f4d6ff3d2868fb7e9d
46.385382
250
0.622029
5.41085
false
false
false
false
vandilsonlima/VLPin
VLPin/Classes/UIView+VLPin_Center.swift
1
1218
// // UIView+VLPin_Center.swift // Pods-VLPin_Example // // Created by Vandilson Lima on 09/07/17. // import UIKit public typealias CenterConstraints = (x: NSLayoutConstraint, y: NSLayoutConstraint) public extension UIView { @discardableResult public func makeCenterX(equalTo view: UIView, constant: CGFloat = 0, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: constant) return make(view: view, constraint: constraint, priority: priority) } @discardableResult public func makeCenterY(equalTo view: UIView, constant: CGFloat = 0, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: constant) return view.make(view: view, constraint: constraint, priority: priority) } @discardableResult public func makeCenter(equalTo view: UIView) -> CenterConstraints { return (makeCenterX(equalTo: view), makeCenterY(equalTo: view)) } }
mit
004e0601da988a96a6831694020ad0e1
37.0625
118
0.700328
4.991803
false
false
false
false
shujincai/DouYu
DouYu/DouYu/Classes/Home/Controller/HomeViewController.swift
1
3398
// // HomeViewController.swift // DouYu // // Created by pingtong on 2017/6/16. // Copyright © 2017年 PTDriver. All rights reserved. // import UIKit private let KTitleViewH: CGFloat = 40 class HomeViewController: UIViewController { //MARK: -懒加载属性 lazy var pageTitleView: PageTitleView = { let titleFrame = CGRect(x: 0, y: KStatusBarH+KNavigationBarH, width: KScreenW, height: KTitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() lazy var pageContentView : PageContentView = {[weak self] in //确定内容的frame let contentH = KScreenH - KStatusBarH - KNavigationBarH - KTitleViewH - KTabBarH let contentFrame = CGRect(x: 0, y: KStatusBarH + KNavigationBarH + KTitleViewH, width: KScreenW, height: contentH) //确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) for _ in 0..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() //设置UI界面 setupUI() } } // MARK: -设置UI界面 extension HomeViewController { func setupUI() { //不需要调整UIscrollView的内边距 automaticallyAdjustsScrollViewInsets = false //设置导航栏 setNavigationBar() view.addSubview(pageTitleView) //添加ContentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } private func setNavigationBar() { //设置左侧Item let btn = UIButton() btn.setImage(UIImage(named: "logo"), for: .normal) btn.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") //设置右侧Item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "viewHistoryIcon", hightImageName: "viewHistoryIconHL", size: size) let searchItem = UIBarButtonItem(imageName: "searchBtnIcon", hightImageName: "searchBtnIconHL", size: size) let qrcodeItem = UIBarButtonItem(imageName:"scanIcon" , hightImageName: "scanIconHL", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } //MARK:- 遵守PageTitleViewDelegate协议 extension HomeViewController: PageTitleViewDelegate { func pageTitleView(titleView: PageTitleView, selectdIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } } //MARK:- 遵守PageContentViewDelegate协议 extension HomeViewController: PageContentViewDelegate { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
23bdaea82ee184d8ef2922447ec6addf
36.918605
156
0.678933
4.852679
false
false
false
false
RocketChat/Rocket.Chat.iOS
Scripts/Localize.swift
1
11673
#!/usr/bin/env xcrun --sdk macosx swift // swiftlint:disable all import Foundation // WHAT // 1. Find Missing keys in other Localisation files // 2. Find potentially untranslated keys // 3. Find Duplicate keys // 4. Find Unused keys and generate script to delete them all at once // MARK: Start Of Configurable Section /* You can enable or disable the script whenever you want */ let enabled = true /* Flag to determine whether unused strings should be an error */ let careAboutUnused = false /* Flag to determine whether potentially untranslated strings should be a warning */ let careAboutUntranslated = false /* Put your path here, example -> Resources/Localizations/Languages */ let relativeLocalizableFolders = "/Rocket.Chat/Resources" /* This is the path of your source folder which will be used in searching for the localization keys you actually use in your project */ let relativeSourceFolder = "/Rocket.Chat" /* Those are the regex patterns to recognize localizations. */ let patterns = [ "NSLocalized(Format)?String\\(\\s*@?\"([\\w\\.]+)\"", // Swift and Objc Native "Localizations\\.((?:[A-Z]{1}[a-z]*[A-z]*)*(?:\\.[A-Z]{1}[a-z]*[A-z]*)*)", // Laurine Calls "L10n.tr\\(key: \"(\\w+)\"", // SwiftGen generation "ypLocalized\\(\"(.*)\"\\)", "\"(.*)\".localized" // "key".localized pattern ] /* Those are the keys you don't want to be recognized as "unused" For instance, Keys that you concatenate will not be detected by the parsing so you want to add them here in order not to create false positives :) */ let ignoredFromUnusedKeys = [String]() /* example let ignoredFromUnusedKeys = [ "NotificationNoOne", "NotificationCommentPhoto", "NotificationCommentHisPhoto", "NotificationCommentHerPhoto" ] */ let masterLanguage = "en" /* Sanitizing files will remove comments, empty lines and order your keys alphabetically. */ let sanitizeFiles = false /* Determines if there are multiple localizations or not. */ let singleLanguage = false // MARK: End Of Configurable Section // MARK: - if enabled == false { print("Localization check cancelled") exit(000) } // Detect list of supported languages automatically func listSupportedLanguages() -> [String] { var sl = [String]() let path = FileManager.default.currentDirectoryPath + relativeLocalizableFolders if !FileManager.default.fileExists(atPath: path) { print("Invalid configuration: \(path) does not exist.") exit(1) } let enumerator: FileManager.DirectoryEnumerator? = FileManager.default.enumerator(atPath: path) let extensionName = "lproj" print("Found these languages:") while let element = enumerator?.nextObject() as? String { if element.hasSuffix(extensionName) { print(element) let name = element.replacingOccurrences(of: ".\(extensionName)", with: "") sl.append(name) } } return sl } let supportedLanguages = listSupportedLanguages() var ignoredFromSameTranslation = [String:[String]]() let path = FileManager.default.currentDirectoryPath + relativeLocalizableFolders var numberOfWarnings = 0 var numberOfErrors = 0 struct LocalizationFiles { var name = "" var keyValue = [String:String]() var linesNumbers = [String:Int]() init(name: String) { self.name = name process() } mutating func process() { if sanitizeFiles { removeCommentsFromFile() removeEmptyLinesFromFile() sortLinesAlphabetically() } let location = singleLanguage ? "\(path)/Localizable.strings" : "\(path)/\(name).lproj/Localizable.strings" if let string = try? String(contentsOfFile: location, encoding: .utf8) { let lines = string.components(separatedBy: CharacterSet.newlines) keyValue = [String:String]() let pattern = "\"(.*)\" = \"(.+)\";" let regex = try? NSRegularExpression(pattern: pattern, options: []) var ignoredTranslation = [String]() for (lineNumber, line) in lines.enumerated() { let range = NSRange(location:0, length:(line as NSString).length) // Ignored pattern let ignoredPattern = "\"(.*)\" = \"(.+)\"; *\\/\\/ *ignore-same-translation-warning" let ignoredRegex = try? NSRegularExpression(pattern: ignoredPattern, options: []) if let ignoredMatch = ignoredRegex?.firstMatch(in:line, options: [], range: range) { let key = (line as NSString).substring(with: ignoredMatch.range(at:1)) ignoredTranslation.append(key) } if let firstMatch = regex?.firstMatch(in: line, options: [], range: range) { let key = (line as NSString).substring(with: firstMatch.range(at:1)) let value = (line as NSString).substring(with: firstMatch.range(at:2)) if let _ = keyValue[key] { let str = "\(path)/\(name).lproj" + "/Localizable.strings:\(linesNumbers[key]!): " + "error: [Redundance] \"\(key)\" " + "is redundant in \(name.uppercased()) file" print(str) numberOfErrors += 1 } else { keyValue[key] = value linesNumbers[key] = lineNumber+1 } } } print(ignoredFromSameTranslation) ignoredFromSameTranslation[name] = ignoredTranslation } } func rebuildFileString(from lines: [String]) -> String { return lines.reduce("") { (r: String, s: String) -> String in return (r == "") ? (r + s) : (r + "\n" + s) } } func removeEmptyLinesFromFile() { let location = "\(path)/\(name).lproj/Localizable.strings" if let string = try? String(contentsOfFile: location, encoding: .utf8) { var lines = string.components(separatedBy: CharacterSet.newlines) lines = lines.filter { $0.trimmingCharacters(in: CharacterSet.whitespaces) != "" } let s = rebuildFileString(from: lines) try? s.write(toFile:location, atomically:false, encoding:String.Encoding.utf8) } } func removeCommentsFromFile() { let location = "\(path)/\(name).lproj/Localizable.strings" if let string = try? String(contentsOfFile: location, encoding: .utf8) { var lines = string.components(separatedBy: CharacterSet.newlines) lines = lines.filter { !$0.hasPrefix("//") } let s = rebuildFileString(from: lines) try? s.write(toFile:location, atomically:false, encoding:String.Encoding.utf8) } } func sortLinesAlphabetically() { let location = "\(path)/\(name).lproj/Localizable.strings" if let string = try? String(contentsOfFile: location, encoding: .utf8) { let lines = string.components(separatedBy: CharacterSet.newlines) var s = "" for (i,l) in sortAlphabetically(lines).enumerated() { s += l if (i != lines.count - 1) { s += "\n" } } try? s.write(toFile:location, atomically:false, encoding:String.Encoding.utf8) } } func removeEmptyLinesFromLines(_ lines:[String]) -> [String] { return lines.filter { $0.trimmingCharacters(in: CharacterSet.whitespaces) != "" } } func sortAlphabetically(_ lines:[String]) -> [String] { return lines.sorted() } } // MARK: - Load Localisation Files in memory let masterLocalizationfile = LocalizationFiles(name: masterLanguage) let localizationFiles = supportedLanguages .filter { $0 != masterLanguage } .map { LocalizationFiles(name: $0) } // MARK: - Detect Unused Keys let sourcesPath = FileManager.default.currentDirectoryPath + relativeSourceFolder let fileManager = FileManager.default let enumerator = fileManager.enumerator(atPath:sourcesPath) var localizedStrings = [String]() while let swiftFileLocation = enumerator?.nextObject() as? String { // checks the extension // TODO OBJC? if swiftFileLocation.hasSuffix(".swift") || swiftFileLocation.hasSuffix(".m") || swiftFileLocation.hasSuffix(".mm") { let location = "\(sourcesPath)/\(swiftFileLocation)" if let string = try? String(contentsOfFile: location, encoding: .utf8) { for p in patterns { let regex = try? NSRegularExpression(pattern: p, options: []) let range = NSRange(location:0, length:(string as NSString).length) //Obj c wa regex?.enumerateMatches(in: string, options: [], range: range, using: { (result, _, _) in if let r = result { let value = (string as NSString).substring(with:r.range(at:r.numberOfRanges-1)) localizedStrings.append(value) } }) } } } } var masterKeys = Set(masterLocalizationfile.keyValue.keys) let usedKeys = Set(localizedStrings) let ignored = Set(ignoredFromUnusedKeys) let unused = masterKeys.subtracting(usedKeys).subtracting(ignored) // Here generate Xcode regex Find and replace script to remove dead keys all at once! var replaceCommand = "\"(" var counter = 0 if careAboutUnused { for v in unused { var str = "\(path)/\(masterLocalizationfile.name).lproj/Localizable.strings:\(masterLocalizationfile.linesNumbers[v]!): " str += "error: [Unused Key] \"\(v)\" is never used" print(str) numberOfErrors += 1 if counter != 0 { replaceCommand += "|" } replaceCommand += v if counter == unused.count-1 { replaceCommand += ")\" = \".*\";" } counter += 1 } } print(replaceCommand) // MARK: - Compare each translation file against master (en) for file in localizationFiles { for k in masterLocalizationfile.keyValue.keys { if let v = file.keyValue[k] { if careAboutUntranslated && v == masterLocalizationfile.keyValue[k] { if !ignoredFromSameTranslation[file.name]!.contains(k) { let str = "\(path)/\(file.name).lproj/Localizable.strings" + ":\(file.linesNumbers[k]!): " + "warning: [Potentialy Untranslated] \"\(k)\"" + "in \(file.name.uppercased()) file doesn't seem to be localized" print(str) numberOfWarnings += 1 } } } else { var str = "\(path)/\(file.name).lproj/Localizable.strings:\(masterLocalizationfile.linesNumbers[k]!): " str += "error: [Missing] \"\(k)\" missing form \(file.name.uppercased()) file" print(str) numberOfErrors += 1 } } } print("Number of warnings : \(numberOfWarnings)") print("Number of errors : \(numberOfErrors)") if numberOfErrors > 0 { exit(1) } // swiftlint:enable all
mit
7852e51b03393375b7da07717b43473c
34.480243
129
0.582455
4.584839
false
false
false
false
darrinhenein/firefox-ios
Client/Frontend/Browser/TabTrayController.swift
1
10159
/* 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 UIKit private let TextBoxHeight = CGFloat(25.0) private let Margin = CGFloat(10) private let CellHeight = TextBoxHeight * 4 // UITableViewController doesn't let us specify a style for recycling views. We override the default style here. private class CustomCell : UITableViewCell { let backgroundHolder: UIView let background: UIImageViewAligned let title: UITextView var margin = Margin override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.backgroundHolder = UIView() self.backgroundHolder.layer.shadowColor = UIColor.blackColor().CGColor self.backgroundHolder.layer.shadowOffset = CGSizeMake(0,0) self.backgroundHolder.layer.shadowOpacity = 0.25 self.backgroundHolder.layer.shadowRadius = 2.0 self.background = UIImageViewAligned() self.background.contentMode = UIViewContentMode.ScaleAspectFill self.background.clipsToBounds = true self.background.userInteractionEnabled = false self.background.alignLeft = true self.background.alignTop = true self.title = UITextView() self.title.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.75) self.title.textColor = UIColor.whiteColor() self.title.textAlignment = NSTextAlignment.Left self.title.userInteractionEnabled = false super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundHolder.addSubview(self.background) addSubview(backgroundHolder) addSubview(self.title) backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) selectionStyle = .None self.title.addObserver(self, forKeyPath: "contentSize", options: .New, context: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { self.title.removeObserver(self, forKeyPath: "contentSize") } private override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { let tv = object as UITextView verticalCenter(tv) } private func verticalCenter(text: UITextView) { var top = (TextBoxHeight - text.contentSize.height) * text.zoomScale / 2.0 top = top < 0.0 ? 0.0 : top text.contentOffset = CGPoint(x: 0, y: -top) } func showFullscreen(container: UIView, table: UITableView) { margin = 0 container.insertSubview(self, atIndex: container.subviews.count) frame = CGRect(x: container.frame.origin.x, y: container.frame.origin.y + ToolbarHeight + StatusBarHeight, width: container.frame.width, height: container.frame.height - ToolbarHeight - ToolbarHeight - StatusBarHeight) // Don't let our cell overlap either of the toolbars title.alpha = 0 setNeedsLayout() } func showAt(offsetY: Int, container: UIView, table: UITableView) { margin = Margin container.insertSubview(self, atIndex: container.subviews.count) frame = CGRect(x: 0, y: ToolbarHeight + StatusBarHeight + CGFloat(offsetY) * CellHeight - table.contentOffset.y, width: container.frame.width, height: CellHeight) title.alpha = 1 setNeedsLayout() } var tab: Browser? { didSet { background.image = tab?.screenshot() title.text = tab?.title } } override func layoutSubviews() { super.layoutSubviews() let w = frame.width - 2 * margin let h = frame.height - margin backgroundHolder.frame = CGRect(x: margin, y: margin, width: w, height: h) background.frame = CGRect(origin: CGPointMake(0,0), size: backgroundHolder.frame.size) title.frame = CGRect(x: 0 + margin, y: 0 + frame.height - TextBoxHeight, width: frame.width - 2 * margin, height: TextBoxHeight) verticalCenter(title) } } class TabTrayController: UIViewController, UITabBarDelegate, UITableViewDelegate, UITableViewDataSource { var tabManager: TabManager! private let CellIdentifier = "CellIdentifier" var tableView: UITableView! var profile: Profile! var toolbar: UIToolbar! override func viewDidLoad() { view.isAccessibilityElement = true view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.") toolbar = UIToolbar() toolbar.backgroundImageForToolbarPosition(.Top, barMetrics: UIBarMetrics.Compact) toolbar.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) view.addSubview(toolbar) let settingsItem = UIBarButtonItem(title: "\u{2699}", style: .Plain, target: self, action: "SELdidClickSettingsItem") settingsItem.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.") let signinItem = UIBarButtonItem(title: NSLocalizedString("Sign in", comment: "Button that leads to Sign in section of the Settings sheet."), style: .Plain, target: self, action: "SELdidClickDone") signinItem.enabled = false let addTabItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "SELdidClickAddTab") let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) toolbar.setItems([settingsItem, spacer, signinItem, spacer, addTabItem], animated: true) tableView = UITableView() tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .None tableView.registerClass(CustomCell.self, forCellReuseIdentifier: CellIdentifier) tableView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) view.addSubview(tableView) toolbar.snp_makeConstraints { make in make.top.equalTo(self.view).offset(StatusBarHeight) make.left.right.equalTo(self.view) return } tableView.snp_makeConstraints { make in make.top.equalTo(self.toolbar.snp_bottom) make.left.right.bottom.equalTo(self.view) } } func SELdidClickDone() { presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } func SELdidClickSettingsItem() { let controller = SettingsNavigationController() controller.profile = profile presentViewController(controller, animated: true, completion: nil) } func SELdidClickAddTab() { tabManager?.addTab() presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let tab = tabManager.getTab(indexPath.item) tabManager.selectTab(tab) dispatch_async(dispatch_get_main_queue()) { _ in self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tabManager.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return CellHeight } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let tab = tabManager.getTab(indexPath.item) let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as CustomCell cell.title.text = tab.title cell.background.image = tab.screenshot(size: CGSize(width: tableView.frame.width, height: CellHeight)) return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let tab = tabManager.getTab(indexPath.item) tabManager.removeTab(tab) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } extension TabTrayController : Transitionable { private func getTransitionCell(options: TransitionOptions, browser: Browser?) -> CustomCell { if let cell = options.moving as? CustomCell { cell.tab = browser return cell } else { let cell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "id") cell.tab = browser options.moving = cell return cell } } func transitionableWillHide(transitionable: Transitionable, options: TransitionOptions) { // Create a fake cell that is shown fullscreen if let container = options.container { let cell = getTransitionCell(options, browser: tabManager.selectedTab) cell.showFullscreen(container, table: tableView) } // Scroll the toolbar off the top toolbar.alpha = 0 toolbar.transform = CGAffineTransformMakeTranslation(0, -ToolbarHeight) } func transitionableWillShow(transitionable: Transitionable, options: TransitionOptions) { if let container = options.container { // Create a fake cell that is at the selected index let cell = getTransitionCell(options, browser: tabManager.selectedTab) cell.showAt(tabManager.selectedIndex, container: container, table: tableView) } // Scroll the toolbar on from the top toolbar.alpha = 1 toolbar.transform = CGAffineTransformIdentity } func transitionableWillComplete(transitionable: Transitionable, options: TransitionOptions) { if let cell = options.moving { cell.removeFromSuperview() } } }
mpl-2.0
8dbf61cdd94752f971f568641291fe43
38.996063
164
0.677232
5.076962
false
false
false
false
iyubinest/Encicla
encicla/location/Location.swift
1
1074
import CoreLocation import RxSwift protocol GPS { func locate() -> Observable<CLLocation> } class DefaultGPS: NSObject, GPS, CLLocationManagerDelegate { private var observer: AnyObserver<CLLocation>? internal func locate() -> Observable<CLLocation> { return Observable.create { observer in self.observer = observer let locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() return Disposables.create { locationManager.delegate = nil } } } internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: Array<CLLocation>) { observer?.on(.next(locations.first!)) observer?.on(.completed) } internal func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse || status == .authorizedAlways { manager.startUpdatingLocation() } else if status == .denied { observer?.on(.error(CLError(.denied))) } } }
mit
d4060bfce3e94d342d8df4dbd07e3ce1
28.027027
70
0.716946
5.396985
false
false
false
false
AnyPresence/justapis-swift-sdk
Source/Request.swift
1
9407
// // Request.swift // JustApisSwiftSDK // // Created by Andrew Palumbo on 12/29/15. // Copyright © 2015 AnyPresence. All rights reserved. // import Foundation /// /// Properties that define a Request. /// public protocol RequestProperties { /// /// Fundamental Request Properties: /// ---- /// The HTTP Verb to use var method:String { get } /// The path to request, relative to the Gateway's baseURL var path:String { get } /// A Dictionary of query string parameters to append to the path var params:QueryParameters? { get } /// HTTP headers to be sent with the request var headers:Headers? { get } /// Any body data to send along with the request var body:NSData? { get } /// Whether HTTP redirects should be followed before a response is handled var followRedirects:Bool { get } /// /// Autoparsing Options, for use with the ContentTypeParser: /// ---- /// Whether to use contentTypeParsing var applyContentTypeParsing:Bool { get } /// The Content-Type to assume for any results, disregarding response headers var contentTypeOverride:String? { get } /// /// Cache Control Options /// ---- /// Whether to check the gateway's response cache before sending var allowCachedResponse:Bool { get } /// How long to store responses in the cache. 0 to not cache response at all var cacheResponseWithExpiration:UInt { get } /// A custom identifier to use for caching. Default is METHOD + PATH + PARAMS var customCacheIdentifier:String? { get } } extension RequestProperties { /// Cache identifier: either the customCacheIdentifier if provided, or METHOD + PATH + PARAMS var cacheIdentifier:String { return customCacheIdentifier ?? "\(self.method) \(self.path)?\(self.params)" } } /// /// Methods that provide a fluent syntax for building Requests /// public protocol RequestBuilderMethods { /// Returns a new Request with the method set to the provided value func method(value:String) -> Self /// Returns a new Request with the path set to the provided value func path(value:String) -> Self /// Returns a new Request with all query params set to the provided value func params(value:QueryParameters?) -> Self /// Returns a new Request with a query parameter of the provided key set to the provided value func param(key:String, _ value:AnyObject?) -> Self /// Returns a new Request with all headers set to the provided value func headers(value:Headers?) -> Self /// Returns a new Request with a header of the provided key set to the provided value func header(key:String, _ value:String?) -> Self /// Returns a new Request with a body set to the provided value func body(value:NSData?) -> Self /// Returns a new Request with the HTTP redirect support flag set to the provided value func followRedirects(value:Bool) -> Self /// Returns a new Request with applyContentTypeParsing set to the provided value func applyContentTypeParsing(value:Bool) -> Self /// Returns a new Request with contentTypeOverride set to the provided value func contentTypeOverride(value:String?) -> Self /// Returns a new Request with allowCachedResponse set to the provided value func allowCachedResponse(value:Bool) -> Self /// Returns a new Request with cacheResponseWithExpiration set to the provided value func cacheResponseWithExpiration(value:UInt) -> Self /// Returns a new Request with customCacheIdentifier set to the provided value func customCacheIdentifier(value:String?) -> Self } extension RequestProperties { func toJsonCompatibleDictionary() -> [String:AnyObject] { var rep = [String:AnyObject]() rep["method"] = self.method rep["path"] = self.path if let params = self.params { rep["params"] = params } else { rep["params"] = NSNull() } rep["headers"] = (self.headers != nil) ? self.headers! : NSNull() rep["body"] = self.body != nil ? self.body?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue:0)) : NSNull() rep["followRedirects"] = self.followRedirects rep["applyContentTypeParsing"] = self.applyContentTypeParsing rep["contentTypeOverride"] = self.contentTypeOverride ?? NSNull() rep["allowCachedResponse"] = self.allowCachedResponse rep["cacheResponseWithExpiration"] = self.cacheResponseWithExpiration rep["customCacheIdentifier"] = self.customCacheIdentifier ?? NSNull() return rep } } /// /// A Request suitable for the JustApi SDK Gateway /// public protocol Request : RequestProperties, RequestBuilderMethods { } /// /// Basic mutable representation of public Request properties /// public struct MutableRequestProperties : RequestProperties { public var method:String public var path:String public var params:QueryParameters? public var headers:Headers? public var body:NSData? public var followRedirects:Bool public var applyContentTypeParsing:Bool = true public var contentTypeOverride:String? = nil public var allowCachedResponse:Bool = false public var cacheResponseWithExpiration:UInt = 0 public var customCacheIdentifier:String? = nil } extension MutableRequestProperties { init?(jsonCompatibleDictionary d:[String:AnyObject]) { guard let method = d["method"] as? String, let path = d["path"] as? String, let followRedirects = d["followRedirects"] as? Bool, let applyContentTypeParsing = d["applyContentTypeParsing"] as? Bool, let allowCachedResponse = d["allowCachedResponse"] as? Bool, let cacheResponseWithExpiration = d["cacheResponseWithExpiration"] as? UInt else { return nil } guard d["params"] != nil && d["headers"] != nil && d["body"] != nil && d["contentTypeOverride"] != nil && d["customCacheIdentifer"] != nil else { return nil } self.method = method self.path = path self.followRedirects = followRedirects self.applyContentTypeParsing = applyContentTypeParsing self.allowCachedResponse = allowCachedResponse self.cacheResponseWithExpiration = cacheResponseWithExpiration if let params = d["params"] as? [String:AnyObject] { self.params = params } if let headers = d["headers"] as? [String:String] { self.headers = headers } if let bodyString = d["body"] as? String { self.body = NSData(base64EncodedString: bodyString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) } if let contentTypeOverride = d["contentTypeOverride"] as? String { self.contentTypeOverride = contentTypeOverride } if let customCacheIdentifier = d["customCacheIdentifer"] as? String { self.customCacheIdentifier = customCacheIdentifier } } } /// /// Provides default request properties to use for specific methods /// public protocol DefaultRequestPropertySet { var get:MutableRequestProperties { get } var post:MutableRequestProperties { get } var put:MutableRequestProperties { get } var delete:MutableRequestProperties { get } } /// /// An flexible implementation of the DefaultRequestPropertySet /// public struct GatewayDefaultRequestProperties : DefaultRequestPropertySet { public let get:MutableRequestProperties public let post:MutableRequestProperties public let put:MutableRequestProperties public let delete:MutableRequestProperties public init( get:MutableRequestProperties? = nil, post:MutableRequestProperties? = nil, put:MutableRequestProperties? = nil, delete:MutableRequestProperties? = nil) { self.get = get ?? MutableRequestProperties(method:"GET", path:"/", params:nil, headers:nil, body:nil, followRedirects:true, applyContentTypeParsing: true, contentTypeOverride: nil, allowCachedResponse: false, cacheResponseWithExpiration: kGatewayDefaultCacheExpiration, customCacheIdentifier: nil) self.post = post ?? MutableRequestProperties(method:"POST", path:"/", params:nil, headers:nil, body:nil, followRedirects:true, applyContentTypeParsing: true, contentTypeOverride: nil, allowCachedResponse: false, cacheResponseWithExpiration: 0, customCacheIdentifier: nil) self.put = put ?? MutableRequestProperties(method:"PUT", path:"/", params:nil, headers:nil, body:nil, followRedirects:true, applyContentTypeParsing: true, contentTypeOverride: nil, allowCachedResponse: false, cacheResponseWithExpiration: 0, customCacheIdentifier: nil) self.delete = delete ?? MutableRequestProperties(method:"DELETE", path:"/", params:nil, headers:nil, body:nil, followRedirects:true, applyContentTypeParsing: true, contentTypeOverride: nil, allowCachedResponse: false, cacheResponseWithExpiration: 0, customCacheIdentifier: nil) } }
mit
c2af0c152a5bc8289ebfdf018d82739e
34.49434
305
0.672762
4.878631
false
false
false
false
SergioEstevao/FontMetrics
FontMetrics/Classes/FontManager.swift
1
3583
import Foundation import UIKit class FontManager: ObservableObject { static let downloadedFonts = "DownloadedFonts" var fontsDownloaded = [String: String]() @Published private(set) var fontFamilies: [String: [String]] = [:] static let shared = FontManager() init() { loadFonts() } static func ensureCustomFontsAreLoaded() { FontManager.shared.loadFonts() } private func loadFonts() { guard let dict = UserDefaults.standard.object(forKey: FontManager.downloadedFonts) as? [String: String] else { refreshFonts() return } fontsDownloaded = dict for (fontName, fileName) in fontsDownloaded { guard let fontURL = FontManager.fontFolder()?.appendingPathComponent(fileName), let data = try? Data(contentsOf: fontURL, options: .uncached) else { fontsDownloaded.removeValue(forKey: fontName) continue } let _ = try? UIFont.registerFontFrom(data: data) } refreshFonts() } @discardableResult func addFont(fromURL url: URL) throws -> String { let data = try Data(contentsOf: url, options: .uncached) let name = try UIFont.registerFontFrom(data: data) guard let baseFolder = FontManager.fontFolder() else { return "" } let fileName = uniqueFilename(withPrefix: name, andExtension: "ttf") let fontPath = baseFolder.appendingPathComponent(fileName) try data.write(to: fontPath, options: [.atomic]) fontsDownloaded[name] = fileName // save it to userDefaults UserDefaults.standard.set(fontsDownloaded, forKey: FontManager.downloadedFonts) UserDefaults.standard.synchronize() refreshFonts() return name } @discardableResult func removeFont(withName name: String) throws -> Bool { guard let urlPath = fontsDownloaded[name], let url = URL(string: urlPath) else { return false } try? FileManager.default.removeItem(at: url) fontsDownloaded.removeValue(forKey: name) let _ = try UIFont.unregisterFont(named: name) // save it to userDefaults UserDefaults.standard.set(fontsDownloaded, forKey: FontManager.downloadedFonts) UserDefaults.standard.synchronize() return true } func isUserFont(withName name: String) -> Bool { return fontsDownloaded[name] != nil } //MARK: - folder helper methods private static func fontFolder() -> URL? { let possibleURLs = FileManager.default.urls(for: .documentDirectory, in: [.userDomainMask]) guard let documentsDirectory = possibleURLs.first else { return nil } let fontsFolder = documentsDirectory.appendingPathComponent(downloadedFonts, isDirectory: true) do { try FileManager.default.createDirectory(at: fontsFolder, withIntermediateDirectories: true, attributes: nil) } catch { return nil } return fontsFolder } private func uniqueFilename(withPrefix prefix: String, andExtension extension: String) -> String { let guid = ProcessInfo.processInfo.globallyUniqueString let uniqueFileName = "\(prefix)_\(guid).\(`extension`)" return uniqueFileName } func refreshFonts() { fontFamilies = UIFont.fontFamilies } }
mit
ce37fe344aa8486b23da9ec273c6593a
29.887931
120
0.618755
5.118571
false
false
false
false
khizkhiz/swift
test/IRGen/objc.swift
1
4361
// RUN: rm -rf %t && mkdir %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo // CHECK: [[TYPE:%swift.type]] = type // CHECK: [[BLAMMO:%C4objc6Blammo]] = type // CHECK: [[MYBLAMMO:%C4objc8MyBlammo]] = type // CHECK: [[TEST2:%C4objc5Test2]] = type // CHECK: [[OBJC:%objc_object]] = type // CHECK: [[ID:%V4objc2id]] = type <{ %Ps9AnyObject_ }> // CHECK: [[GIZMO:%CSo5Gizmo]] = type // CHECK: [[RECT:%VSC4Rect]] = type // CHECK: [[FLOAT:%Sf]] = type // CHECK: @"\01L_selector_data(bar)" = private global [4 x i8] c"bar\00", section "__TEXT,__objc_methname,cstring_literals", align 1 // CHECK: @"\01L_selector(bar)" = private externally_initialized global i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(bar)", i64 0, i64 0), section "__DATA,__objc_selrefs,literal_pointers,no_dead_strip", align 8 // CHECK: @_TMnVSC4Rect = linkonce_odr hidden constant // CHECK: @_TMVSC4Rect = linkonce_odr hidden global // CHECK: @"\01L_selector_data(acquiesce)" // CHECK-NOT: @"\01L_selector_data(disharmonize)" // CHECK: @"\01L_selector_data(eviscerate)" struct id { var data : AnyObject } // Exporting something as [objc] doesn't make it an ObjC class. @objc class Blammo { } // Class and methods are [objc] by inheritance. class MyBlammo : Blammo { func foo() {} // CHECK: define hidden void @_TFC4objc8MyBlammo3foofT_T_([[MYBLAMMO]]*) {{.*}} { // CHECK: call {{.*}} @rt_swift_release // CHECK: ret void } // Class and methods are [objc] by inheritance. class Test2 : Gizmo { func foo() {} // CHECK: define hidden void @_TFC4objc5Test23foofT_T_([[TEST2]]*) {{.*}} { // CHECK: call {{.*}} @objc_release // CHECK: ret void dynamic func bar() {} } // Test @nonobjc. class Contrarian : Blammo { func acquiesce() {} @nonobjc func disharmonize() {} @nonobjc func eviscerate() {} } class Octogenarian : Contrarian { // Override of @nonobjc is @objc again unless made @nonobjc. @nonobjc override func disharmonize() {} // Override of @nonobjc can be @objc. @objc override func eviscerate() {} } // CHECK: define hidden %objc_object* @_TF4objc5test0{{.*}}(%objc_object*) // CHECK-NOT: call {{.*}} @swift_unknownRetain // CHECK: call {{.*}} @swift_unknownRetain // CHECK-NOT: call {{.*}} @swift_unknownRelease // CHECK: call {{.*}} @swift_unknownRelease // CHECK: ret %objc_object* func test0(arg: id) -> id { var x : id x = arg var y = x return y } func test1(cell: Blammo) {} // CHECK: define hidden void @_TF4objc5test1{{.*}}([[BLAMMO]]*) {{.*}} { // CHECK: call {{.*}} @rt_swift_release // CHECK: ret void // FIXME: These ownership convention tests should become SILGen tests. func test2(v: Test2) { v.bar() } func test3() -> NSObject { return Gizmo() } // Normal message send with argument, no transfers. func test5(g: Gizmo) { Gizmo.inspect(g) } // The argument to consume: is __attribute__((ns_consumed)). func test6(g: Gizmo) { Gizmo.consume(g) } // fork is __attribute__((ns_consumes_self)). func test7(g: Gizmo) { g.fork() } // clone is __attribute__((ns_returns_retained)). func test8(g: Gizmo) { g.clone() } // duplicate has an object returned at +0. func test9(g: Gizmo) { g.duplicate() } func test10(g: Gizmo, r: Rect) { Gizmo.run(with: r, andGizmo:g); } // Force the emission of the Rect metadata. func test11_helper<T>(t: T) {} // NSRect's metadata needs to be uniqued at runtime using getForeignTypeMetadata. // CHECK-LABEL: define hidden void @_TF4objc6test11FVSC4RectT_ // CHECK: call %swift.type* @swift_getForeignTypeMetadata({{.*}} @_TMVSC4Rect func test11(r: Rect) { test11_helper(r) } class WeakObjC { weak var obj: NSObject? weak var id: AnyObject? init() { var foo = obj var bar: AnyObject? = id } } // rdar://17528908 // CHECK: i32 1, !"Objective-C Version", i32 2} // CHECK: i32 1, !"Objective-C Image Info Version", i32 0} // CHECK: i32 1, !"Objective-C Image Info Section", !"__DATA, __objc_imageinfo, regular, no_dead_strip"} // 512 == (2 << 8). 2 is the Swift ABI version. // CHECK: i32 4, !"Objective-C Garbage Collection", i32 768} // CHECK: i32 1, !"Swift Version", i32 3}
apache-2.0
9e34f5510bcc2ed4338f8efd63ac349a
29.496503
234
0.647099
3.099502
false
true
false
false
rxwei/Parsey
Sources/Parsey/Lexer.swift
1
7187
// // Lexer.swift // Parsey // // Created by Richard Wei on 8/25/16. // // internal extension Parse { init(input: ParserInput, target: Target, length: Int) { self.rest = input.dropFirst(length) self.range = input.location..<rest.location self.target = target } } public enum Lexer {} /// TODO: Remove duplicate code in here public extension Lexer { static func character(_ char: Character) -> Parser<String> { return Parser { input in guard let first = input.first, first == char else { throw ParseFailure(expected: String(char), input: input) } return Parse(input: input, target: String(first), length: 1) } } static func anyCharacter(in range: ClosedRange<Character>) -> Parser<String> { return Parser { input in guard let first = input.first, range.contains(first) else { throw ParseFailure(expected: "a character within range \(range)", input: input) } return Parse(input: input, target: String(first), length: 1) } } static func anyCharacter<S: Sequence>(in characters: S) -> Parser<String> where S.Element == Character { return Parser { input in guard let first = input.first, characters.contains(first) else { throw ParseFailure( expected: "a character within {\(characters.map{"\"\($0)\""}.joined(separator: ", "))}", input: input ) } return Parse(input: input, target: String(first), length: 1) } } static func anyCharacter(in characterString: String) -> Parser<String> { return anyCharacter(in: Array(characterString[characterString.startIndex ..< characterString.endIndex])) } static func anyCharacter(except exception: Character) -> Parser<String> { return Parser { input in guard let first = input.first, first != exception else { throw ParseFailure(expected: "any character except \"\(exception)\"", input: input) } return Parse(input: input, target: String(first), length: 1) } } static func anyCharacter<S: Sequence>(except exceptions: S) -> Parser<String> where S.Element == Character { return Parser { input in guard let first = input.first, !exceptions.contains(first) else { throw ParseFailure( expected: "any character except {\(exceptions.map{"\"\($0)\""}.joined(separator: ", "))}", input: input ) } return Parse(input: input, target: String(first), length: 1) } } } /// MARK: - Primitives public extension Lexer { static let space = character(" ") static let tab = character("\t") static let whitespace = anyCharacter(in: [" ", "\t"]) static let whitespaces = whitespace+ static let newLine = anyCharacter(in: ["\n", "\r"]) static let newLines = newLine+ static let upperLetter = anyCharacter(in: "A"..."Z") static let lowerLetter = anyCharacter(in: "a"..."z") static let letter = upperLetter | lowerLetter static let digit = anyCharacter(in: "0"..."9") static let unsignedInteger = digit.manyConcatenated() static let unsignedDecimal = unsignedInteger + character(".") + unsignedInteger static let signedInteger = anyCharacter(in: "+-").maybeEmpty() + unsignedInteger static let signedDecimal = anyCharacter(in: "+-").maybeEmpty() + unsignedDecimal static let end = Parser<String> { input in guard input.isEmpty else { throw ParseFailure(input: input) } return Parse(target: "", range: input.location..<input.location, rest: input) } } import Foundation /// MARK: - String Matching public extension Lexer { /// Parse a string until it sees a character in the exception list, /// without consuming the character static func string<S: Sequence>(until exception: S) -> Parser<String> where S.Element == Character { return anyCharacter(except: exception).manyConcatenated() } /// Parse a string until it sees a the exception character, /// without consuming the character static func string(until character: Character) -> Parser<String> { return anyCharacter(except: character).manyConcatenated() } /// Match regular expression static func regex(_ pattern: String) -> Parser<String> { return Parser<String> { input in #if !os(macOS) && !swift(>=3.1) /// Swift standard library inconsistency! let regex = try RegularExpression(pattern: pattern, options: [ .dotMatchesLineSeparators ]) #else let regex = try NSRegularExpression(pattern: pattern, options: [ .dotMatchesLineSeparators ]) #endif let text = input.text let matches = regex.matches( in: text, options: [ .anchored ], range: NSMakeRange(0, input.stream.count) ) guard let match = matches.first else { throw ParseFailure(expected: "pattern \"\(pattern)\"", input: input) } /// UTF16 conversion is safe here since NSRegularExpression results are based on UTF16 let matchedText = String(text.utf16.prefix(match.range.length))! return Parse(input: input, target: matchedText, length: matchedText.count) } } /// Match any token in the collection /// - Note: Since this is based on regular expression matching, you should be careful /// with special regex characters static func token<C: Collection>(in tokens: C) -> Parser<String> where C.Element == String { return regex(tokens.joined(separator: "|")) } /// Parse an explicit token static func token(_ token: String) -> Parser<String> { return Parser<String> { input in guard input.starts(with: token) else { throw ParseFailure(expected: "token \"\(token)\"", input: input) } return Parse(input: input, target: token, length: token.count) } } } /// MARK: - Combinator extension on strings public extension Parser { func amid(_ surrounding: String) -> Parser<Target> { return amid(Lexer.token(surrounding)) } func between(_ left: String, _ right: String) -> Parser<Target> { return between(Lexer.token(left), Lexer.token(right)) } static func ~~>(_ lhs: String, _ rhs: Parser<Target>) -> Parser<Target> { return Lexer.token(lhs) ~~> rhs } static func !~~>(_ lhs: String, _ rhs: Parser<Target>) -> Parser<Target> { return Lexer.token(lhs) !~~> rhs } static func <~~(_ lhs: Parser<Target>, _ rhs: String) -> Parser<Target> { return lhs <~~ Lexer.token(rhs) } static func !<~~(_ lhs: Parser<Target>, _ rhs: String) -> Parser<Target> { return lhs !<~~ Lexer.token(rhs) } }
mit
d640ccc07b672c2d89d05559016326f8
34.579208
112
0.593572
4.475093
false
false
false
false
iankunneke/TIY-Assignmnts
26 OutaSwift/26 OutaSwift/TimeViewController.swift
1
2634
// // ViewController.swift // 26 OutaSwift // // Created by ian kunneke on 7/20/15. // Copyright (c) 2015 The Iron Yard. All rights reserved. // import UIKit protocol TimeCircuitsDatePickerDelegate { func destinationDateWasChosen(destinationDate: NSDate) } class TimeViewController: UIViewController, TimeCircuitsDatePickerDelegate { @IBOutlet weak var destinationTimeLabel: UILabel! @IBOutlet weak var presentTimeLabel: UILabel! @IBOutlet weak var lastTimeDepartedLabel: UILabel! @IBOutlet weak var currentSpeedLabel: UILabel! let formatter = NSDateFormatter() var speed = 0 var timer: NSTimer? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "Time Circuits" let formatString = NSDateFormatter.dateFormatFromTemplate("MMMddyyyy", options: 0, locale: NSLocale .currentLocale()) formatter.dateFormat = formatString presentTimeLabel.text = formatter .stringFromDate(NSDate()) currentSpeedLabel.text = "\(speed) MPH" lastTimeDepartedLabel.text = "--- -- ----" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDestinationDatePickerSegue" { let datePickerVC = segue.destinationViewController as! DatePickerViewController datePickerVC.delegate = self } } func destinationDateWasChosen(destinationDate: NSDate) { destinationTimeLabel.text = formatter .stringFromDate(destinationDate) } @IBAction func travelBack(sender: UIButton) { startTimer() } func startTimer() { timer = NSTimer .scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateSpeed", userInfo: nil, repeats: true) } func stopTimer() { timer? .invalidate() timer = nil } func updateSpeed() { if speed < 88 { speed++ currentSpeedLabel.text = "\(speed) MPH!" } else { stopTimer() lastTimeDepartedLabel.text = presentTimeLabel.text presentTimeLabel.text = destinationTimeLabel.text speed = 0 currentSpeedLabel.text = "\(speed) MPH" } } }
cc0-1.0
2c27ad14f7da2e7afea7197653c3af70
25.079208
129
0.618451
5.104651
false
false
false
false
Draveness/RbSwift
Sources/String+Enumeration.swift
2
1922
// // Enumeration.swift // RbSwift // // Created by draveness on 19/03/2017. // Copyright © 2017 draveness. All rights reserved. // import Foundation // MARK: - Enumeration public extension String { /// Splits str using the supplied parameter as the record separator `\n`, /// passing each substring with separator in turn to the supplied closure. /// /// var results: [String] = [] /// "Hello\nWorld".eachLine { /// results.append($0) /// } /// results #=> ["Hello\n", "World"] /// /// If a zero-length record separator is supplied, the string is split into /// paragraphs delimited by multiple successive newlines. /// /// var results: [String] = [] /// "Hello\nWorld".eachLine("l") { /// results.append($0) /// } /// results #=> ["Hel", "l", "o\nWorl", "d"] /// /// - Parameters: /// - separator: A string used to separate the receiver string /// - closure: A closure reveives String as parameter which is separated by the separator func eachLine(_ separator: String = "\n", closure: (String) -> Void) { var lines = self.lines(separator) for (index, line) in lines.enumerated() { if index != lines.count - 1 { lines[index] = line + separator } } lines.filter { $0.length > 0 }.forEach(closure) } /// Passes each character as string in the receiver to the given closure. /// /// var results: [String] = [] /// "Hello\n".eachChar { /// results.append($0) /// } /// results #=> ["H", "e", "l", "l", "o", "\n"] /// /// - Parameter closure: A closure receives all characters as String func eachChar(closure: (String) -> Void) { for char in self.chars { closure(char) } } }
mit
2d53f9f2e9cbc4cfd9eb0809945313dc
32.12069
95
0.532015
4.018828
false
false
false
false
ringly/IOS-Pods-DFU-Library
iOSDFULibrary/Classes/Implementation/DFUServiceInitiator.swift
1
13065
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth /** The DFUServiceInitiator object should be used to send a firmware update to a remote BLE target compatible with the Nordic Semiconductor's DFU (Device Firmware Update). A `delegate`, `progressDelegate` and `logger` may be specified in order to receive status information. */ @objc public class DFUServiceInitiator : NSObject { //MARK: - Internal variables internal let centralManager : CBCentralManager internal let target : CBPeripheral internal var file : DFUFirmware? //MARK: - Public variables /** The service delegate is an object that will be notified about state changes of the DFU Service. Setting it is optional but recommended. */ public weak var delegate: DFUServiceDelegate? /** An optional progress delegate will be called only during upload. It notifies about current upload percentage and speed. */ public weak var progressDelegate: DFUProgressDelegate? /** The logger is an object that should print given messages to the user. It is optional. */ public weak var logger: LoggerDelegate? /// The DFU control point characteristic UUID to search for public var controlPointCharacteristicUUID = DFUControlPoint.defaultUUID /// The DFU packet characteristic UUID to search for public var packetCharacteristicUUID = DFUPacket.defaultUUID /** The selector object is used when the device needs to disconnect and start advertising with a different address to avodi caching problems, for example after switching to the Bootloader mode, or during sending a firmware containing a Softdevice (or Softdevice and Bootloader) and the Application. After flashing the first part (containing the Softdevice), the device restarts in the DFU Bootloader mode and may (since SDK 8.0.0) start advertising with an address incremented by 1. The peripheral specified in the `init` may no longer be used as there is no device advertising with its address. The DFU Service will scan for a new device and connect to the first device returned by the selector. The default selecter returns the first device with the required DFU Service UUID in the advertising packet (Secure or Legacy DFU Service UUID). Ignore this property if not updating Softdevice and Application from one ZIP file or your */ public var peripheralSelector: DFUPeripheralSelectorDelegate /** The number of packets of firmware data to be received by the DFU target before sending a new Packet Receipt Notification. If this value is 0, the packet receipt notification will be disabled by the DFU target. Default value is 12. Higher values (~20+), or disabling it, may speed up the upload process, but also cause a buffer overflow and hang the Bluetooth adapter. Maximum verified values were 29 for iPhone 6 Plus or 22 for iPhone 7, both iOS 10.1. */ public var packetReceiptNotificationParameter: UInt16 = 12 /** **Legacy DFU only.** Setting this property to true will prevent from jumping to the DFU Bootloader mode in case there is no DFU Version characteristic. Use it if the DFU operation can be handled by your device running in the application mode. If the DFU Version characteristic exists, the information whether to begin DFU operation, or jump to bootloader, is taken from the characteristic's value. The value returned equal to 0x0100 (read as: minor=1, major=0, or version 0.1) means that the device is in the application mode and buttonless jump to DFU Bootloader is supported. Currently, the following values of the DFU Version characteristic are supported: **No DFU Version characteristic** - one of the first implementations of DFU Service. The device may support only Application update (version from SDK 4.3.0), may support Soft Device, Bootloader and Application update but without buttonless jump to bootloader (SDK 6.0.0) or with buttonless jump (SDK 6.1.0). The DFU Library determines whether the device is in application mode or in DFU Bootloader mode by counting number of services: if no DFU Service found - device is in app mode and does not support buttonless jump, if the DFU Service is the only service found (except General Access and General Attribute services) - it assumes it is in DFU Bootloader mode and may start DFU immediately, if there is at least one service except DFU Service - the device is in application mode and supports buttonless jump. In the lase case, you want to perform DFU operation without jumping - call the setForceDfu(force:Bool) method with parameter equal to true. **0.1** - Device is in a mode that supports buttonless jump to the DFU Bootloader **0.5** - Device can handle DFU operation. Extended Init packet is required. Bond information is lost in the bootloader mode and after updating an app. Released in SDK 7.0.0. **0.6** - Bond information is kept in bootloader mode and may be kept after updating application (DFU Bootloader must be configured to preserve the bond information). **0.7** - The SHA-256 firmware hash is used in the Extended Init Packet instead of CRC-16. This feature is transparent for the DFU Service. **0.8** - The Extended Init Packet is signed using the private key. The bootloader, using the public key, is able to verify the content. Released in SDK 9.0.0 as experimental feature. Caution! The firmware type (Application, Bootloader, SoftDevice or SoftDevice+Bootloader) is not encrypted as it is not a part of the Extended Init Packet. A change in the protocol will be required to fix this issue. By default the DFU Library will try to switch the device to the DFU Bootloader mode if it finds more services then one (DFU Service). It assumes it is already in the bootloader mode if the only service found is the DFU Service. Setting the forceDfu to true (YES) will prevent from jumping in these both cases. */ public var forceDfu = false /** Set this flag to true to enable experimental buttonless feature in Secure DFU. When the experimental Buttonless DFU Service is found on a device, the service will use it to switch the device to the bootloader mode, connect to it in that mode and proceed with DFU. **Please, read the information below before setting it to true.** In the SDK 12.x the Buttonless DFU feature for Secure DFU was experimental. It is NOT recommended to use it: it was not properly tested, had implementation bugs (e.g. https://devzone.nordicsemi.com/question/100609/sdk-12-bootloader-erased-after-programming/) and does not required encryption and therefore may lead to DOS attack (anyone can use it to switch the device to bootloader mode). However, as there is no other way to trigger bootloader mode on devices without a button, this DFU Library supports this service, but the feature must be explicitly enabled here. Be aware, that setting this flag to false will no protect your devices from this kind of attacks, as an attacker may use another app for that purpose. To be sure your device is secure remove this experimental service from your device. Spec: Buttonless DFU Service UUID: 8E400001-F315-4F60-9FB8-838830DAEA50 Buttonless DFU characteristic UUID: 8E400001-F315-4F60-9FB8-838830DAEA50 (the same) Enter Bootloader Op Code: 0x01 Correct return value: 0x20-01-01 , where: 0x20 - Response Op Code 0x01 - Request Code 0x01 - Success The device should disconnect and restart in DFU mode after sending the notification. In SDK 13 this issue will be fixed by a proper implementation (bonding required, passing bond information to the bootloader, encryption, well tested). It is recommended to use this new service when SDK 13 (or later) is out. TODO: fix the docs when SDK 13 is out. */ public var enableUnsafeExperimentalButtonlessServiceInSecureDfu = false //MARK: - Public API /** Creates the DFUServiceInitializer that will allow to send an update to the given peripheral. The peripheral should be disconnected prior to calling start() method. The DFU service will automatically connect to the device, check if it has required DFU service (return a delegate callback if does not have such), jump to the DFU Bootloader mode if necessary and perform the DFU. Proper delegate methods will be called during the process. - parameter central manager that will be used to connect to the peripheral - parameter target: the DFU target peripheral - returns: the initiator instance - seeAlso: peripheralSelector property - a selector used when scanning for a device in DFU Bootloader mode in case you want to update a Softdevice and Application from a single ZIP Distribution Packet. */ public init(centralManager: CBCentralManager, target: CBPeripheral) { self.centralManager = centralManager // Just to be sure that manager is not scanning self.centralManager.stopScan() self.target = target // Default peripheral selector will choose the service UUID as a filter self.peripheralSelector = DFUPeripheralSelector() super.init() } /** Sets the file with the firmware. The file must be specified before calling `start()` method, and must not be nil. - parameter file: The firmware wrapper object - returns: the initiator instance to allow chain use */ public func with(firmware file: DFUFirmware) -> DFUServiceInitiator { self.file = file return self } /** Starts sending the specified firmware to the DFU target. When started, the service will automatically connect to the target, switch to DFU Bootloader mode (if necessary), and send all the content of the specified firmware file in one or two connections. Two connections will be used if a ZIP file contains a Soft Device and/or Bootloader and an Application. First the Soft Device and/or Bootloader will be transferred, then the service will disconnect, reconnect to the (new) Bootloader again and send the Application (unless the target supports receiving all files in a single connection). The current version of the DFU Bootloader, due to memory limitations, may receive together only a Softdevice and Bootloader. - returns: A DFUServiceController object that can be used to control the DFU operation. */ public func start() -> DFUServiceController? { // The firmware file must be specified before calling `start()` if file == nil { delegate?.dfuError(.fileNotSpecified, didOccurWithMessage: "Firmare not specified") return nil } let controller = DFUServiceController() let selector = DFUServiceSelector(initiator: self, controller: controller, controlPointCharacteristicUUID: controlPointCharacteristicUUID, packetCharacteristicUUID: packetCharacteristicUUID) controller.executor = selector selector.start() return controller } }
bsd-3-clause
68fdda37e44168734a98bc3cd587fd7f
52.987603
198
0.727976
5.131579
false
false
false
false
zacwest/ZSWTappableLabel
Example/ZSWTappableLabel/Accessibility/AccessibilitySwiftViewController.swift
1
4191
// // AccessibilitySwiftViewController.swift // ZSWTappableLabel_Example // // Created by Zac West on 4/20/19. // Copyright © 2019 Zachary West. All rights reserved. // import UIKit import ZSWTappableLabel import SafariServices class SwiftViewLinkCustomAction: UIAccessibilityCustomAction { let range: NSRange let attributes: [NSAttributedString.Key: Any] init(name: String, target: Any?, selector: Selector, range: NSRange, attributes: [NSAttributedString.Key: Any]) { self.attributes = attributes self.range = range super.init(name: name, target: target, selector: selector) } } class AccessibilitySwiftViewController: UIViewController, ZSWTappableLabelTapDelegate, ZSWTappableLabelAccessibilityDelegate { let label: ZSWTappableLabel = { let label = ZSWTappableLabel() label.adjustsFontForContentSizeCategory = true return label }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white label.tapDelegate = self label.accessibilityDelegate = self label.textAlignment = .center let string = NSLocalizedString("Privacy Policy", comment: "") let attributes: [NSAttributedString.Key: Any] = [ .tappableRegion: true, .tappableHighlightedBackgroundColor: UIColor.lightGray, .tappableHighlightedForegroundColor: UIColor.white, .font: UIFont.preferredFont(forTextStyle: .body), .foregroundColor: UIColor.blue, .underlineStyle: NSUnderlineStyle.single.rawValue, .link: URL(string: "http://imgur.com/gallery/VgXCk")! ] label.attributedText = NSAttributedString(string: string, attributes: attributes) view.addSubview(label) label.snp.makeConstraints { make in make.edges.equalTo(view) } } @objc func viewLink(_ action: SwiftViewLinkCustomAction) -> Bool { guard let URL = action.attributes[.link] as? URL else { return false } let alertController = UIAlertController(title: URL.absoluteString, message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("Open URL", comment: ""), style: .default, handler: { [weak self] _ in guard let this = self else { return } this.show(SFSafariViewController(url: URL), sender: this) })) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) return true } // MARK: - ZSWTappableLabelTapDelegate func tappableLabel(_ tappableLabel: ZSWTappableLabel, tappedAt idx: Int, withAttributes attributes: [NSAttributedString.Key : Any] = [:]) { guard let URL = attributes[.link] as? URL else { return } show(SFSafariViewController(url: URL), sender: self) } // MARK: - ZSWTappableLabelAccessibilityDelegate func tappableLabel(_ tappableLabel: ZSWTappableLabel, accessibilityCustomActionsForCharacterRange characterRange: NSRange, withAttributesAtStart attributes: [NSAttributedString.Key : Any] = [:]) -> [UIAccessibilityCustomAction] { return [ SwiftViewLinkCustomAction( name: NSLocalizedString("View Link Address", comment: ""), target: self, selector: #selector(viewLink(_:)), range: characterRange, attributes: attributes ) ] } func tappableLabel(_ tappableLabel: ZSWTappableLabel, accessibilityLabelForCharacterRange characterRange: NSRange, withAttributesAtStart attributes: [NSAttributedString.Key : Any] = [:]) -> String? { if attributes[.link] != nil { return NSLocalizedString("Privacy Policy Label For Accessibility", comment: "Replaces the Privacy Policy text in the label") } else { return nil } } }
mit
f1ee11e6795b297a1d7194e6d2666c3c
37.440367
233
0.643198
5.097324
false
false
false
false
Shannon-s-Dreamland/Charts
Charts/Classes/Renderers/CombinedChartRenderer.swift
2
6808
// // CombinedChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics public class CombinedChartRenderer: ChartDataRendererBase { public weak var chart: CombinedChartView? /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled = false /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled = true /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled = true internal var _renderers = [ChartDataRendererBase]() internal var _drawOrder: [CombinedChartView.DrawOrder] = [.Bar, .Bubble, .Line, .Candle, .Scatter] public init(chart: CombinedChartView, animator: ChartAnimator, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart createRenderers() } /// Creates the renderers needed for this combined-renderer in the required order. Also takes the DrawOrder into consideration. internal func createRenderers() { _renderers = [ChartDataRendererBase]() guard let chart = chart, animator = animator else { return } for order in drawOrder { switch (order) { case .Bar: if (chart.barData !== nil) { _renderers.append(BarChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Line: if (chart.lineData !== nil) { _renderers.append(LineChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Candle: if (chart.candleData !== nil) { _renderers.append(CandleStickChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Scatter: if (chart.scatterData !== nil) { _renderers.append(ScatterChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Bubble: if (chart.bubbleData !== nil) { _renderers.append(BubbleChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break } } } public override func drawData(context context: CGContext) { for renderer in _renderers { renderer.drawData(context: context) } } public override func drawValues(context context: CGContext) { for renderer in _renderers { renderer.drawValues(context: context) } } public override func drawExtras(context context: CGContext) { for renderer in _renderers { renderer.drawExtras(context: context) } } public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { for renderer in _renderers { var data: ChartData? if renderer is BarChartRenderer { data = (renderer as! BarChartRenderer).dataProvider?.barData } else if renderer is LineChartRenderer { data = (renderer as! LineChartRenderer).dataProvider?.lineData } else if renderer is CandleStickChartRenderer { data = (renderer as! CandleStickChartRenderer).dataProvider?.candleData } else if renderer is ScatterChartRenderer { data = (renderer as! ScatterChartRenderer).dataProvider?.scatterData } else if renderer is BubbleChartRenderer { data = (renderer as! BubbleChartRenderer).dataProvider?.bubbleData } let dataIndex = data == nil ? nil : (chart?.data as? CombinedChartData)?.allData.indexOf(data!) let dataIndices = indices.filter{ $0.dataIndex == dataIndex || $0.dataIndex == -1 } renderer.drawHighlighted(context: context, indices: dataIndices) } } public override func calcXBounds(chart chart: BarLineChartViewBase, xAxisModulus: Int) { for renderer in _renderers { renderer.calcXBounds(chart: chart, xAxisModulus: xAxisModulus) } } /// - returns: the sub-renderer object at the specified index. public func getSubRenderer(index index: Int) -> ChartDataRendererBase? { if (index >= _renderers.count || index < 0) { return nil } else { return _renderers[index] } } /// Returns all sub-renderers. public var subRenderers: [ChartDataRendererBase] { get { return _renderers } set { _renderers = newValue } } // MARK: Accessors /// - returns: true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; } /// - returns: true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; } /// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [CombinedChartView.DrawOrder] { get { return _drawOrder } set { if (newValue.count > 0) { _drawOrder = newValue } } } }
apache-2.0
4737d631ceaf08ac74e81cfac752b7d1
31.265403
138
0.576087
5.603292
false
false
false
false
gdimaggio/SwiftlyRater
SwiftlyRater/Reachability/Reachability.swift
1
9771
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Reachability.swift version 2.2beta2 import SystemConfiguration import Foundation enum ReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue } let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() DispatchQueue.main.async { reachability.reachabilityChanged() } } class Reachability { typealias NetworkReachable = (Reachability) -> () typealias NetworkUnreachable = (Reachability) -> () enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } var whenReachable: NetworkReachable? var whenUnreachable: NetworkUnreachable? var reachableOnWWAN: Bool var currentReachabilityString: String { return "\(currentReachabilityStatus)" } var currentReachabilityStatus: NetworkStatus { guard isReachable else { return .notReachable } if isReachableViaWiFi { return .reachableViaWiFi } if isRunningOnDevice { return .reachableViaWWAN } return .notReachable } fileprivate var previousFlags: SCNetworkReachabilityFlags? fileprivate var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate var reachabilityRef: SCNetworkReachability? fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability") required public init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } convenience init?(hostname: String) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref) } convenience init?() { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return nil } self.init(reachabilityRef: ref) } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } } extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard let reachabilityRef = reachabilityRef, !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an intial check reachabilitySerialQueue.async { self.reachabilityChanged() } notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } guard let reachabilityRef = reachabilityRef else { return } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** var isReachable: Bool { guard isReachableFlagSet else { return false } if isConnectionRequiredAndTransientFlagSet { return false } if isRunningOnDevice { if isOnWWANFlagSet && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet } var isReachableViaWiFi: Bool { // Check we're reachable guard isReachableFlagSet else { return false } // If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return true } // Check we're NOT on WWAN return !isOnWWANFlagSet } var description: String { let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X" let R = isReachableFlagSet ? "R" : "-" let c = isConnectionRequiredFlagSet ? "c" : "-" let t = isTransientConnectionFlagSet ? "t" : "-" let i = isInterventionRequiredFlagSet ? "i" : "-" let C = isConnectionOnTrafficFlagSet ? "C" : "-" let D = isConnectionOnDemandFlagSet ? "D" : "-" let l = isLocalAddressFlagSet ? "l" : "-" let d = isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func reachabilityChanged() { let flags = reachabilityFlags guard previousFlags != flags else { return } let block = isReachable ? whenReachable : whenUnreachable block?(self) NotificationCenter.default.post(name: ReachabilityChangedNotification, object:self) previousFlags = flags } var isOnWWANFlagSet: Bool { #if os(iOS) return reachabilityFlags.contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return reachabilityFlags.contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return reachabilityFlags.contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return reachabilityFlags.contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return reachabilityFlags.contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return reachabilityFlags.contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return reachabilityFlags.contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return reachabilityFlags.contains(.isLocalAddress) } var isDirectFlagSet: Bool { return reachabilityFlags.contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } var reachabilityFlags: SCNetworkReachabilityFlags { guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() } var flags = SCNetworkReachabilityFlags() let gotFlags = withUnsafeMutablePointer(to: &flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } else { return SCNetworkReachabilityFlags() } } }
mit
81909cbdae5f4bbfc629dfc369b2a263
31.89899
137
0.658889
5.987132
false
false
false
false
danielallsopp/Charts
Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift
15
3350
// // BubbleChartDataSet.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics public class BubbleChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBubbleChartDataSet { // MARK: - Data functions and accessors internal var _xMax = Double(0.0) internal var _xMin = Double(0.0) internal var _maxSize = CGFloat(0.0) public var xMin: Double { return _xMin } public var xMax: Double { return _xMax } public var maxSize: CGFloat { return _maxSize } public var normalizeSizeEnabled: Bool = true public var isNormalizeSizeEnabled: Bool { return normalizeSizeEnabled } public override func calcMinMax(start start: Int, end: Int) { let yValCount = self.entryCount if yValCount == 0 { return } let entries = yVals as! [BubbleChartDataEntry] // need chart width to guess this properly var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } _lastStart = start _lastEnd = end _yMin = yMin(entries[start]) _yMax = yMax(entries[start]) for i in start.stride(through: endValue, by: 1) { let entry = entries[i] let ymin = yMin(entry) let ymax = yMax(entry) if (ymin < _yMin) { _yMin = ymin } if (ymax > _yMax) { _yMax = ymax } let xmin = xMin(entry) let xmax = xMax(entry) if (xmin < _xMin) { _xMin = xmin } if (xmax > _xMax) { _xMax = xmax } let size = largestSize(entry) if (size > _maxSize) { _maxSize = size } } } private func yMin(entry: BubbleChartDataEntry) -> Double { return entry.value } private func yMax(entry: BubbleChartDataEntry) -> Double { return entry.value } private func xMin(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func xMax(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func largestSize(entry: BubbleChartDataEntry) -> CGFloat { return entry.size } // MARK: - Styling functions and accessors /// Sets/gets the width of the circle that surrounds the bubble when highlighted public var highlightCircleWidth: CGFloat = 2.5 // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! BubbleChartDataSet copy._xMin = _xMin copy._xMax = _xMax copy._maxSize = _maxSize copy.highlightCircleWidth = highlightCircleWidth return copy } }
apache-2.0
65339e7af3f17a5e68c57cc2db6e2682
22.928571
92
0.522985
5.01497
false
false
false
false
simeonpp/home-hunt
ios-client/HomeHunt/Data/UsersData.swift
1
1412
import Foundation class UsersData: HttpRequesterDelegate { var url: String? var httpRequester: HttpRequesterBase? var delegate: UsersDataDelegate? func register(user: User) { self.httpRequester?.postJson(toUrl: "\(self.url!)/register", withBody: user.toDict(), andHeaders: nil, identifier: UsersDataIdentifiers.register.rawValue) } func login(user: User) { self.httpRequester?.postJson(toUrl: "\(self.url!)/login", withBody: user.toDict(), andHeaders: nil, identifier: UsersDataIdentifiers.login.rawValue) } func didCompletePostJSON(result: Any, identifier: String) { let resultAsDict = result as! Dictionary<String, Any> switch identifier { case UsersDataIdentifiers.register.rawValue: let user = User(withDict: resultAsDict) self.delegate?.didRegistered(user: user) case UsersDataIdentifiers.login.rawValue: let error = resultAsDict["error"] if (error == nil) { self.delegate?.didLogin(cookie: resultAsDict["cookie"]! as! String, error: nil) } else { let errorDict = error as! Dictionary<String, Any> let errorMessage = errorDict["message"] as! String self.delegate?.didLogin(cookie: "__no_cookie__", error: errorMessage) } default: return } } }
mit
1975e3ff95eb66b1716b5f5793e9f42a
39.342857
162
0.627479
4.496815
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Controllers/Teams/Team/Team@Event/TeamSummaryViewController.swift
1
20976
import CoreData import Foundation import TBAData import TBAKit import UIKit protocol TeamSummaryViewControllerDelegate: AnyObject { func teamInfoSelected(_ team: Team) func matchSelected(_ match: Match) } private enum TeamSummarySection: Int { case teamInfo case eventInfo case nextMatch case playoffInfo case qualInfo case lastMatch } private enum TeamSummaryItem: Hashable { case teamInfo(team: Team) case status(status: String) case rank(rank: Int, total: Int) case record(wlt: WLT, dqs: Int? = nil) case average(average: Double) case breakdown(rankingInfo: String) case alliance(allianceStatus: String) case match(match: Match, team: Team? = nil) func hash(into hasher: inout Hasher) { switch self { case .teamInfo(let team): hasher.combine(team) case .status(let status): hasher.combine(status) case .rank(let rank, let total): hasher.combine(rank) hasher.combine(total) case .record(let wlt, let dqs): hasher.combine(wlt) hasher.combine(dqs) case .average(let average): hasher.combine(average) case .breakdown(let rankingInfo): hasher.combine(rankingInfo) case .alliance(let allianceStatus): hasher.combine(allianceStatus) case .match(let match, let team): hasher.combine(match) hasher.combine(team) } } static func == (lhs: TeamSummaryItem, rhs: TeamSummaryItem) -> Bool { switch (lhs, rhs) { case (.teamInfo(let lhsTeam), .teamInfo(let rhsTeam)): return lhsTeam == rhsTeam case (.status(let lhsStatus), .status(let rhsStatus)): return lhsStatus == rhsStatus case (.rank(let lhsRank, let lhsTotal), .rank(let rhsRank, let rhsTotal)): return lhsRank == rhsRank && lhsTotal == rhsTotal case (.record(let lhsWlt, let lhsDqs), .record(let rhsWlt, let rhsDqs)): return lhsWlt.wins == rhsWlt.wins && lhsWlt.losses == rhsWlt.losses && lhsWlt.ties == rhsWlt.ties && lhsDqs == rhsDqs case (.average(let lhsAverage), .average(let rhsAverage)): return lhsAverage == rhsAverage case (.breakdown(let lhsRankingInfo), .breakdown(let rhsRankingInfo)): return lhsRankingInfo == rhsRankingInfo case (.alliance(let lhsAllianceStatus), .alliance(let rhsAllianceStatus)): return lhsAllianceStatus == rhsAllianceStatus case (.match(let lhsMatch, let lhsTeam), .match(let rhsMatch, let rhsTeam)): return lhsMatch == rhsMatch && lhsTeam == rhsTeam default: return false } } } class TeamSummaryViewController: TBATableViewController { weak var delegate: TeamSummaryViewControllerDelegate? private let team: Team private let event: Event private var dataSource: TableViewDataSource<TeamSummarySection, TeamSummaryItem>! private var eventStatus: EventStatus? { didSet { if let eventStatus = eventStatus { contextObserver.observeObject(object: eventStatus, state: .updated) { (_, _) in self.executeUpdate(self.updateEventStatusItems) } } else { contextObserver.observeInsertions { (eventStatuses) in self.eventStatus = eventStatuses.first self.executeUpdate(self.updateEventStatusItems) } } } } private func executeUpdate(_ update: @escaping () -> ()) { OperationQueue.main.addOperation { update() } } // MARK: - Observable typealias ManagedType = EventStatus lazy var contextObserver: CoreDataContextObserver<EventStatus> = { return CoreDataContextObserver(context: persistentContainer.viewContext) }() lazy var observerPredicate: NSPredicate = { return EventStatus.predicate(eventKey: event.key, teamKey: team.key) }() init(team: Team, event: Event, dependencies: Dependencies) { self.team = team self.event = event super.init(dependencies: dependencies) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.registerReusableCell(ReverseSubtitleTableViewCell.self) tableView.registerReusableCell(InfoTableViewCell.self) tableView.registerReusableCell(MatchTableViewCell.self) setupDataSource() tableView.dataSource = dataSource // Since we leverage didSet, we need to do this *after* initilization eventStatus = EventStatus.findOrFetch(in: persistentContainer.viewContext, matching: observerPredicate) executeUpdate(updateTeamInfo) executeUpdate(updateEventStatusItems) executeUpdate(updateNextMatchItem) executeUpdate(updateLastMatchItem) } // MARK: - Private Methods private func setupDataSource() { dataSource = TableViewDataSource<TeamSummarySection, TeamSummaryItem>(tableView: tableView, cellProvider: { (tableView, indexPath, item) -> UITableViewCell? in switch item { case .teamInfo(let team): return TeamSummaryViewController.tableView(tableView, cellForTeam: team, at: indexPath) case .status(let status): return TeamSummaryViewController.tableView(tableView, reverseSubtitleCellWithTitle: "Status", subtitle: status, at: indexPath) case .rank(let rank, let total): return TeamSummaryViewController.tableView(tableView, cellForRank: rank, totalTeams: total, at: indexPath) case .record(let record, let dqs): return TeamSummaryViewController.tableView(tableView, cellForRecord: record, dqs: dqs, at: indexPath) case .average(let average): return TeamSummaryViewController.tableView(tableView, cellForAverage: average, at: indexPath) case .breakdown(let breakdown): return TeamSummaryViewController.tableView(tableView, cellForBreakdown: breakdown, at: indexPath) case .alliance(let allianceStatus): return TeamSummaryViewController.tableView(tableView, cellForAllianceStatus: allianceStatus, at: indexPath) case .match(let match, let team): return TeamSummaryViewController.tableView(tableView, cellForMatch: match, team: team, at: indexPath) } }) dataSource.delegate = self dataSource.statefulDelegate = self } private func updateTeamInfo() { var snapshot = dataSource.snapshot() let teamInfoSummaryItem = TeamSummaryItem.teamInfo(team: team) snapshot.deleteSections([.teamInfo]) snapshot.insertSection(.teamInfo, atIndex: TeamSummarySection.teamInfo.rawValue) snapshot.appendItems([teamInfoSummaryItem], toSection: .teamInfo) dataSource.apply(snapshot, animatingDifferences: false) } private func updateEventStatusItems() { var snapshot = dataSource.snapshot() // MARK: - Summary let teamStatusSummaryItem: TeamSummaryItem? = { // https://github.com/the-blue-alliance/the-blue-alliance/blob/5337b3b7767f909e251f7aff04d6a0f73b5820f0/helpers/event_team_status_helper.py#L36 if let status = eventStatus?.playoff?.status, let level = eventStatus?.playoff?.level { let compLevel = MatchCompLevel(rawValue: level)?.level ?? level if status == "playing", let record = eventStatus?.playoff?.currentRecord { return .status(status: "Currently \(record.stringValue) in the \(compLevel)") } else if status == "eliminated" { return .status(status: "Eliminated in the \(compLevel)") } else if status == "won" { if level == "f" { return .status(status: "Won the event") } else { return .status(status: "Won the \(compLevel)") } } } return nil }() let hasEventInfoSection = snapshot.indexOfSection(.eventInfo) != nil let eventInfoItems = hasEventInfoSection ? snapshot.itemIdentifiers(inSection: .eventInfo) : [] let existingTeamStatusSummaryItems = eventInfoItems.filter({ switch $0 { case .status(_): return true; default: return false } }) snapshot.deleteItems(existingTeamStatusSummaryItems) if let teamStatusSummaryItem = teamStatusSummaryItem { snapshot.insertSection(.eventInfo, atIndex: TeamSummarySection.eventInfo.rawValue) snapshot.insertItem(teamStatusSummaryItem, inSection: .eventInfo, atIndex: 0) } else if hasEventInfoSection, eventInfoItems.isEmpty { snapshot.deleteSections([.eventInfo]) } // MARK: - Playoff Info var playoffInfoItems: [TeamSummaryItem] = [] // Alliance if let allianceStatus = eventStatus?.allianceStatus, allianceStatus != "--" { playoffInfoItems.append(.alliance(allianceStatus: allianceStatus)) } // Record if let record = eventStatus?.playoff?.record { playoffInfoItems.append(.record(wlt: record)) } // Average if let average = eventStatus?.playoff?.playoffAverage { playoffInfoItems.append(.average(average: average)) } snapshot.deleteSections([.playoffInfo]) if !playoffInfoItems.isEmpty { snapshot.insertSection(.playoffInfo, atIndex: TeamSummarySection.playoffInfo.rawValue) snapshot.appendItems(playoffInfoItems, toSection: .playoffInfo) } // MARK: - Qual Info var qualInfoItems: [TeamSummaryItem] = [] // Rank if let rank = eventStatus?.qual?.ranking?.rank, let total = eventStatus?.qual?.numTeams { qualInfoItems.append(.rank(rank: rank, total: total)) } // Record if let record = eventStatus?.qual?.ranking?.record { qualInfoItems.append(.record(wlt: record, dqs: eventStatus?.qual?.ranking?.dq)) } // Average if let average = eventStatus?.qual?.ranking?.qualAverage { qualInfoItems.append(.average(average: average)) } // Breakdown if let rankingInfo = eventStatus?.qual?.ranking?.rankingInfoString { qualInfoItems.append(.breakdown(rankingInfo: rankingInfo)) } snapshot.deleteSections([.qualInfo]) if !qualInfoItems.isEmpty { snapshot.insertSection(.qualInfo, atIndex: TeamSummarySection.qualInfo.rawValue) snapshot.appendItems(qualInfoItems, toSection: .qualInfo) } dataSource.apply(snapshot, animatingDifferences: false) executeUpdate(updateNextMatchItem) executeUpdate(updateLastMatchItem) } private func updateNextMatchItem() { var snapshot = dataSource.snapshot() let nextMatch: Match? = { if let nextMatchKey = eventStatus?.nextMatchKey, let match = Match.forKey(nextMatchKey, in: persistentContainer.viewContext) { return match } return nil }() let nextMatchItem: TeamSummaryItem? = { if let nextMatch = nextMatch, event.isHappeningNow { return .match(match: nextMatch, team: team) } return nil }() snapshot.deleteSections([.nextMatch]) if let nextMatchItem = nextMatchItem { snapshot.insertSection(.nextMatch, atIndex: TeamSummarySection.nextMatch.rawValue) snapshot.appendItems([nextMatchItem], toSection: .nextMatch) } dataSource.apply(snapshot, animatingDifferences: false) } private func updateLastMatchItem() { var snapshot = dataSource.snapshot() let lastMatch: Match? = { if let lastMatchKey = eventStatus?.lastMatchKey, let match = Match.forKey(lastMatchKey, in: persistentContainer.viewContext) { return match } return nil }() let lastMatchItem: TeamSummaryItem? = { if let lastMatch = lastMatch, event.isHappeningNow { return .match(match: lastMatch, team: team) } return nil }() snapshot.deleteSections([.lastMatch]) if let lastMatchItem = lastMatchItem { snapshot.insertSection(.lastMatch, atIndex: TeamSummarySection.lastMatch.rawValue) snapshot.appendItems([lastMatchItem], toSection: .lastMatch) } dataSource.apply(snapshot, animatingDifferences: false) } // MARK: TableViewDataSourceDelegate override func title(forSection section: Int) -> String? { let snapshot = dataSource.snapshot() let section = snapshot.sectionIdentifiers[section] if section == .eventInfo { return "Summary" } else if section == .nextMatch { return "Next Match" } else if section == .playoffInfo { return "Playoffs" } else if section == .qualInfo { return "Qualifications" } else if section == .lastMatch { return "Most Recent Match" } return nil } // MARK: - Table View Cells private static func tableView(_ tableView: UITableView, cellForTeam team: Team, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(indexPath: indexPath) as InfoTableViewCell cell.viewModel = InfoCellViewModel(team: team) cell.accessoryType = .disclosureIndicator cell.selectionStyle = .none return cell } private static func tableView(_ tableView: UITableView, cellForRank rank: Int, totalTeams total: Int, at indexPath: IndexPath) -> UITableViewCell { return self.tableView( tableView, reverseSubtitleCellWithTitle: "Rank", subtitle: "\(rank)\(rank.suffix) (of \(total))", at: indexPath ) } private static func tableView(_ tableView: UITableView, cellForRecord record: WLT, dqs: Int?, at indexPath: IndexPath) -> UITableViewCell { let subtitle: String = { if let dqs = dqs, dqs > 0 { return "\(record.stringValue) (\(dqs) DQ)" } return record.stringValue }() return self.tableView( tableView, reverseSubtitleCellWithTitle: "Record", subtitle: subtitle, at: indexPath ) } private static func tableView(_ tableView: UITableView, cellForAverage average: Double, at indexPath: IndexPath) -> UITableViewCell { return self.tableView( tableView, reverseSubtitleCellWithTitle: "Average", subtitle: "\(average)", at: indexPath ) } private static func tableView(_ tableView: UITableView, cellForAllianceStatus allianceStatus: String, at indexPath: IndexPath) -> UITableViewCell { return self.tableView(tableView, reverseSubtitleCellWithTitle: "Alliance", subtitle: allianceStatus, at: indexPath) } private static func tableView(_ tableView: UITableView, cellForBreakdown breakdown: String, at indexPath: IndexPath) -> UITableViewCell { return self.tableView(tableView, reverseSubtitleCellWithTitle: "Ranking Breakdown", subtitle: breakdown, at: indexPath) } private static func tableView(_ tableView: UITableView, reverseSubtitleCellWithTitle title: String, subtitle: String, at indexPath: IndexPath) -> ReverseSubtitleTableViewCell { let cell = tableView.dequeueReusableCell(indexPath: indexPath) as ReverseSubtitleTableViewCell cell.titleLabel.text = title // Strip our subtitle string of HTML tags - they're expensive to render and useless. let sanitizedSubtitle = subtitle.replacingOccurrences(of: "<b>", with: "").replacingOccurrences(of: "</b>", with: "") cell.subtitleLabel.text = sanitizedSubtitle cell.accessoryType = .none cell.selectionStyle = .none return cell } private static func tableView(_ tableView: UITableView, cellForMatch match: Match, team: Team?, at indexPath: IndexPath) -> MatchTableViewCell { let cell = tableView.dequeueReusableCell(indexPath: indexPath) as MatchTableViewCell cell.viewModel = MatchViewModel(match: match, team: team) return cell } // MARK: - Table View Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let item = dataSource.itemIdentifier(for: indexPath) else { return } switch item { case .teamInfo(let team): delegate?.teamInfoSelected(team) case .match(let match, _): delegate?.matchSelected(match) default: break } } } extension TeamSummaryViewController: Refreshable { var refreshKey: String? { return "\(team.key)@\(event.key)_status" } var automaticRefreshInterval: DateComponents? { return DateComponents(hour: 1) } var automaticRefreshEndDate: Date? { // Automatically refresh team summary until the event is over return event.endDate?.endOfDay() } var isDataSourceEmpty: Bool { return dataSource.isDataSourceEmpty } @objc func refresh() { var finalOperation: Operation! var eventOperation: TBAKitOperation? if event.name == nil { eventOperation = tbaKit.fetchEvent(key: event.key, completion: { [self] (result, notModified) in guard case .success(let object) = result, let event = object, !notModified else { return } let context = persistentContainer.newBackgroundContext() context.performChangesAndWait({ Event.insert(event, in: context) }, saved: { [unowned self] in self.markTBARefreshSuccessful(self.tbaKit, operation: eventOperation!) }, errorRecorder: errorRecorder) }) } let teamKey = team.key // Refresh Team@Event status var teamStatusOperation: TBAKitOperation! teamStatusOperation = tbaKit.fetchTeamStatus(key: teamKey, eventKey: event.key) { [self] (result, notModified) in guard case .success(let object) = result, let status = object, !notModified else { return } // Kickoff refreshes for our Match objects, add them as dependents for reloading data refreshStatusMatches(status, finalOperation) let context = persistentContainer.newBackgroundContext() context.performChangesAndWait({ let event = context.object(with: self.event.objectID) as! Event event.insert(status) }, saved: { [unowned self] in self.markTBARefreshSuccessful(tbaKit, operation: teamStatusOperation) }, errorRecorder: errorRecorder) } finalOperation = addRefreshOperations([eventOperation, teamStatusOperation].compactMap({ $0 })) } func refreshStatusMatches(_ status: TBAEventStatus, _ dependentOperation: Operation) { let callSets = zip([status.lastMatchKey, status.nextMatchKey].compactMap({ $0 }), [updateLastMatchItem, updateNextMatchItem]) let ops = callSets.compactMap { [weak self] in return self?.fetchMatch($0, $1) } ops.forEach { dependentOperation.addDependency($0) } refreshOperationQueue.addOperations(ops, waitUntilFinished: false) } func fetchMatch(_ key: String, _ update: @escaping () -> ()) -> TBAKitOperation? { var operation: TBAKitOperation! operation = tbaKit.fetchMatch(key: key) { [self] (result, notModified) in guard case .success(let object) = result, let match = object, !notModified else { return } let context = persistentContainer.newBackgroundContext() context.performChangesAndWait({ Match.insert(match, in: context) }, saved: { [unowned self] in self.tbaKit.storeCacheHeaders(operation) self.executeUpdate(update) }, errorRecorder: errorRecorder) } return operation } } extension TeamSummaryViewController: Stateful { var noDataText: String? { return "No status for team at event" } }
mit
13141b14ebbf109dd5939d9226f83de0
37
180
0.632771
4.951841
false
false
false
false
PedroTrujilloV/TIY-Assignments
12--The-Temple-of-Core-Data/CountOnMe-Ben/CountOnMe/CounterTableViewController.swift
1
4610
// // CounterTableViewController.swift // CountOnMe // // Created by Ben Gohlke on 10/19/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreData class CounterTableViewController: UITableViewController, UITextFieldDelegate { // Retrieve the managed object context from the AppDelegate let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var counters = Array<Counter>() override func viewDidLoad() { super.viewDidLoad() title = "Counters" navigationItem.leftBarButtonItem = self.editButtonItem() let fetchRequest = NSFetchRequest(entityName: "Counter") // Execute the fetch request, and cast the results to an array of LogItem objects do { let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Counter] counters = fetchResults! } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return counters.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CounterCell", forIndexPath: indexPath) as! CounterCell // Configure the cell... let aCounter = counters[indexPath.row] if aCounter.title == nil { cell.counterTitleTextField.becomeFirstResponder() } else { cell.counterTitleTextField.text = aCounter.title } cell.countLabel.text = "\(aCounter.count)" return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let aCounter = counters[indexPath.row] counters.removeAtIndex(indexPath.row) managedObjectContext.deleteObject(aCounter) saveContext() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } // MARK: - UITextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { var rc = false if textField.text != "" { rc = true let contentView = textField.superview let cell = contentView?.superview as! CounterCell let indexPath = tableView.indexPathForCell(cell) let aCounter = counters[indexPath!.row] aCounter.title = textField.text textField.resignFirstResponder() saveContext() } return rc } // MARK: - Action Handlers @IBAction func stepperValueChanged(sender: UIStepper) { let contentView = sender.superview let cell = contentView?.superview as! CounterCell let indexPath = tableView.indexPathForCell(cell) let aCounter = counters[indexPath!.row] let countAsInt = Int16(sender.value) aCounter.count = countAsInt cell.countLabel.text = "\(countAsInt)" saveContext() } @IBAction func addCounter(sender: UIBarButtonItem) { let newCounter = NSEntityDescription.insertNewObjectForEntityForName("Counter", inManagedObjectContext: managedObjectContext) as! Counter counters.append(newCounter) tableView.reloadData() } // MARK: - Private func saveContext() { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } }
cc0-1.0
b935dd1a83234489974bad76ffcfb5a9
29.328947
155
0.62877
5.648284
false
false
false
false
ru-kio/Hydra
FXHydra/FXSearchAudiosController.swift
3
7905
// // FXSearchAudiosController.swift // FXHydra // // Created by kioshimafx on 4/3/16. // Copyright © 2016 FXSolutions. All rights reserved. // import UIKit class FXSearchAudiosController: UITableViewController , UISearchResultsUpdating, UISearchControllerDelegate { let bitrateImageDark = UIImage(named: "bitrate_background")?.imageByTintColor(UIColor ( red: 0.426, green: 0.4397, blue: 0.4529, alpha: 1.0)) let bitrateImageBlue = UIImage(named: "bitrate_background")?.imageByTintColor(UIColor ( red: 0.0734, green: 0.6267, blue: 0.7817, alpha: 1.0)) var canSearch = true var searchedAudios = Array<FXAudioItemModel>() override func viewDidLoad() { super.viewDidLoad() self.definesPresentationContext = true self.extendedLayoutIncludesOpaqueBars = true self.tableViewStyle() self.tableView.registerClass(FXDefaultMusicCell.self, forCellReuseIdentifier: "FXDefaultMusicCell") // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } func tableViewStyle() { self.tableView.tableFooterView = UIView() self.tableView.separatorInset = UIEdgeInsetsMake(0, 50, 0, 0) self.tableView.indicatorStyle = UIScrollViewIndicatorStyle.White self.definesPresentationContext = true self.extendedLayoutIncludesOpaqueBars = true self.tableView.backgroundColor = UIColor ( red: 0.2228, green: 0.2228, blue: 0.2228, alpha: 1.0 ) self.tableView.separatorColor = UIColor ( red: 0.2055, green: 0.2015, blue: 0.2096, alpha: 1.0 ) self.view.backgroundColor = UIColor ( red: 0.1221, green: 0.1215, blue: 0.1227, alpha: 1.0 ) } func animateTable() { self.tableView.reloadData() //// let cells = tableView.visibleCells let tableHeight: CGFloat = tableView.bounds.size.height for i in cells { let cell: UITableViewCell = i as UITableViewCell cell.transform = CGAffineTransformMakeTranslation(0, tableHeight) } var index = 0 for a in cells { let cell: UITableViewCell = a as UITableViewCell UIView.animateWithDuration(0.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { cell.transform = CGAffineTransformMakeTranslation(0, 0); }, completion: nil) index += 1 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.searchedAudios.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let auidoModel = self.searchedAudios[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("FXDefaultMusicCell", forIndexPath: indexPath) as! FXDefaultMusicCell cell.bindedAudioModel = auidoModel return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let musicModel = self.searchedAudios[indexPath.row] self.drawMusicCell(cell as! FXDefaultMusicCell, audioModel: musicModel) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) FXPlayerService.sharedManager().currentAudiosArray = self.searchedAudios FXPlayerService.sharedManager().currentAudioIndexInArray = indexPath.row FXPlayerService.sharedManager().startPlayAtIndex() self.tableView.updateWithBlock { (tableView) -> Void in tableView.reloadRow(UInt(indexPath.row), inSection: UInt(indexPath.section), withRowAnimation: UITableViewRowAnimation.None) } /// FXInterfaceService.sharedManager().openPlayer() } // MARK: - Drawing cells func drawMusicCell(cell:FXDefaultMusicCell,audioModel:FXAudioItemModel) { cell.audioAristLabel.text = audioModel.artist cell.audioTitleLabel.text = audioModel.title cell.audioTimeLabel.text = audioModel.getDurationString() if FXDataService.sharedManager().checkAudioIdInDownloads(audioModel.audioID) == false { cell.downloadButton.setImage(UIImage(named: "download_button"), forState: UIControlState.Normal) cell.downloadButton.tintColor = UIColor ( red: 0.0, green: 0.8408, blue: 1.0, alpha: 1.0) cell.downloadButton.addTarget(self, action: #selector(FXAllAudiosController.startDownload(_:)), forControlEvents: UIControlEvents.TouchUpInside) } else { cell.downloadButton.hidden = true } /// if audioModel.bitrate > 0 { cell.audioBitrate.text = "\(audioModel.bitrate)" cell.bitRateBackgroundImage.image = self.bitrateImageBlue } else { cell.bitRateBackgroundImage.image = self.bitrateImageDark cell.audioBitrate.text = "●●●" audioModel.getBitrate { (bitrate) -> () in cell.audioBitrate.text = "\(bitrate)" cell.bitRateBackgroundImage.image = self.bitrateImageBlue } } /// } func startDownload(sender:AnyObject?) { log.debug("::: sender \(sender) :::") let superView = sender?.superview!!.superview as! FXDefaultMusicCell let audioModel = superView.bindedAudioModel FXDownloadsPoolService.sharedManager().downloadAudioOnLocalStorage(audioModel) } //MARK: - Search logic func updateSearchResultsForSearchController(searchController: UISearchController) { if canSearch == true { canSearch = false if searchController.searchBar.text != "" { log.debug("\(searchController.searchBar.text)") self.loadSearch(searchController.searchBar.text) } else { self.searchedAudios = Array<FXAudioItemModel>() self.tableView.reloadData() canSearch = true } } } func loadSearch(query: String!) { self.searchedAudios = Array<FXAudioItemModel>() FXApiManager.sharedManager().vk_audiosearch(query!, offset: 0, count: 100) { (audiosArray) in dispatch.async.main({ self.searchedAudios = audiosArray self.tableView.reloadData() self.canSearch = true }) } } }
mit
623b4b7995f9e467322b9f5f07000f53
34.576577
156
0.623829
5.258322
false
false
false
false
hyperconnect/SQLite.swift
Sources/SQLite/Extensions/Cipher.swift
2
3079
#if SQLITE_SWIFT_SQLCIPHER import SQLCipher /// Extension methods for [SQLCipher](https://www.zetetic.net/sqlcipher/). /// @see [sqlcipher api](https://www.zetetic.net/sqlcipher/sqlcipher-api/) extension Connection { /// - Returns: the SQLCipher version public var cipherVersion: String? { return (try? scalar("PRAGMA cipher_version")) as? String } /// Specify the key for an encrypted database. This routine should be /// called right after sqlite3_open(). /// /// @param key The key to use.The key itself can be a passphrase, which is converted to a key /// using [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) key derivation. The result /// is used as the encryption key for the database. /// /// Alternatively, it is possible to specify an exact byte sequence using a blob literal. /// With this method, it is the calling application's responsibility to ensure that the data /// provided is a 64 character hex string, which will be converted directly to 32 bytes (256 bits) /// of key data. /// e.g. x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99' /// @param db name of the database, defaults to 'main' public func key(_ key: String, db: String = "main") throws { try _key_v2(db: db, keyPointer: key, keySize: key.utf8.count) } public func key(_ key: Blob, db: String = "main") throws { try _key_v2(db: db, keyPointer: key.bytes, keySize: key.bytes.count) } /// Change the key on an open database. If the current database is not encrypted, this routine /// will encrypt it. /// To change the key on an existing encrypted database, it must first be unlocked with the /// current encryption key. Once the database is readable and writeable, rekey can be used /// to re-encrypt every page in the database with a new key. public func rekey(_ key: String, db: String = "main") throws { try _rekey_v2(db: db, keyPointer: key, keySize: key.utf8.count) } public func rekey(_ key: Blob, db: String = "main") throws { try _rekey_v2(db: db, keyPointer: key.bytes, keySize: key.bytes.count) } // MARK: - private private func _key_v2(db: String, keyPointer: UnsafePointer<UInt8>, keySize: Int) throws { try check(sqlite3_key_v2(handle, db, keyPointer, Int32(keySize))) try cipher_key_check() } private func _rekey_v2(db: String, keyPointer: UnsafePointer<UInt8>, keySize: Int) throws { try check(sqlite3_rekey_v2(handle, db, keyPointer, Int32(keySize))) } // When opening an existing database, sqlite3_key_v2 will not immediately throw an error if // the key provided is incorrect. To test that the database can be successfully opened with the // provided key, it is necessary to perform some operation on the database (i.e. read from it). private func cipher_key_check() throws { let _ = try scalar("SELECT count(*) FROM sqlite_master;") } } #endif
mit
9719fc73b40a6da4f8c7ecc13d7bff85
45.651515
113
0.659305
3.787208
false
false
false
false
yunzixun/V2ex-Swift
Common/V2EXMentionedBindingParser.swift
1
1559
// // V2EXMentionedBindingParser.swift // V2ex-Swift // // Created by huangfeng on 1/25/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import YYText class V2EXMentionedBindingParser: NSObject ,YYTextParser{ var regex:NSRegularExpression override init() { self.regex = try! NSRegularExpression(pattern: "@(\\S+)\\s", options: [.caseInsensitive]) super.init() } func parseText(_ text: NSMutableAttributedString?, selectedRange: NSRangePointer?) -> Bool { guard let text = text else { return false; } self.regex.enumerateMatches(in: text.string, options: [.withoutAnchoringBounds], range: text.yy_rangeOfAll()) { (result, flags, stop) -> Void in if let result = result { let range = result.range if range.location == NSNotFound || range.length < 1 { return ; } if text.attribute(NSAttributedStringKey(rawValue: YYTextBindingAttributeName), at: range.location, effectiveRange: nil) != nil { return ; } let bindlingRange = NSMakeRange(range.location, range.length-1) let binding = YYTextBinding() binding.deleteConfirm = true ; text.yy_setTextBinding(binding, range: bindlingRange) text.yy_setColor(colorWith255RGB(0, g: 132, b: 255), range: bindlingRange) } } return false; } }
mit
5938af4faef132985d0cfa957040167c
33.622222
152
0.574454
4.664671
false
false
false
false
silan-liu/SwiftDanmuView
SwiftDanmuView/DanmuView/Utils/UIView+Frame.swift
1
1122
// // UIView+Frame.swift // SwiftDanmuView // // Created by liusilan on 2017/4/17. // Copyright © 2017年 silan. All rights reserved. // import Foundation import UIKit extension UIView { var x: CGFloat { get { return self.frame.origin.x } set { var rect = self.frame rect.origin.x = newValue self.frame = rect } } var y: CGFloat { get { return self.frame.origin.y } set { var rect = self.frame rect.origin.y = newValue self.frame = rect } } var width: CGFloat { get { return self.frame.size.width } set { var rect = self.frame rect.size.width = newValue self.frame = rect } } var height: CGFloat { get { return self.frame.size.height } set { var rect = self.frame rect.size.height = newValue self.frame = rect } } }
mit
8b12a2948c37b70fe35033b50ccf484f
17.65
49
0.447721
4.371094
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
Liferay-Screens/Themes/Default/DDL/FormScreenlet/DDLFieldDateTableCell_default.swift
1
2096
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License for more * details. */ import UIKit public class DDLFieldDateTableCell_default: DDLBaseFieldTextboxTableCell_default { @IBOutlet internal var chooseButton: UIButton? { didSet { setButtonDefaultStyle(chooseButton) } } //MARK: Actions @IBAction private func chooseButtonAction(sender: AnyObject) { textField!.becomeFirstResponder() } //MARK: DDLBaseFieldTextboxTableCell override internal func onChangedField() { super.onChangedField() if let fieldValue = field { setFieldPresenter(fieldValue) if fieldValue.currentValue != nil { textField?.text = fieldValue.currentValueAsLabel } } } //MARK: Private methods private func setFieldPresenter(field:DDLField) { func onChange(selectedDate:NSDate!) { field.currentValue = selectedDate textField?.text = field.currentValueAsLabel let fullRange = NSMakeRange(0, count(textField!.text!)) textField(textField, shouldChangeCharactersInRange: fullRange, replacementString: textField!.text!) } let presenter = DTDatePickerPresenter(changeBlock:onChange) presenter.datePicker.datePickerMode = .Date presenter.datePicker.timeZone = NSTimeZone(abbreviation: "GMT") presenter.datePicker.backgroundColor = UIColor.whiteColor() presenter.datePicker.layer.borderColor = UIColor.lightGrayColor().CGColor presenter.datePicker.layer.borderWidth = 1.5 if let currentDate = field.currentValue as? NSDate { presenter.datePicker.setDate(currentDate, animated: false) } textField?.dt_setPresenter(presenter) } }
gpl-3.0
ad0d920f9925f6dbdea44bde05193819
25.871795
82
0.762405
4.142292
false
false
false
false
wang-chuanhui/CHSDK
Source/CHUI/NibDesignable.swift
1
3889
// // NibDesignable.swift // CHSDK // // Created by 王传辉 on 2017/8/4. // Copyright © 2017年 王传辉. All rights reserved. // import UIKit public protocol NibDesignable: NSObjectProtocol { var nibContainerView: UIView { get } func loadNib() -> UIView func nibName() -> String } public extension NibDesignable { func didSetupNib() { } } extension NibDesignable { public func loadNib() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: self.nibName(), bundle: bundle) return nib.instantiate(withOwner: self, options: nil)[0] as! UIView // swiftlint:disable:this force_cast } func setupNib() { let view = self.loadNib() self.nibContainerView.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false view.topAnchor.constraint(equalTo: self.nibContainerView.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: self.nibContainerView.bottomAnchor).isActive = true view.leftAnchor.constraint(equalTo: self.nibContainerView.leftAnchor).isActive = true view.rightAnchor.constraint(equalTo: self.nibContainerView.rightAnchor).isActive = true didSetupNib() } } extension UIView { @objc public var nibContainerView: UIView { return self } open func nibName() -> String { return type(of: self).description().components(separatedBy: ".").last! } } open class NibDesignableView: UIView, NibDesignable { override public init(frame: CGRect) { super.init(frame: frame) self.setupNib() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } } open class NibDesignableTableViewCell: UITableViewCell, NibDesignable { public override var nibContainerView: UIView { return self.contentView } override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setupNib() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } } open class NibDesignableTableViewHeaderFooterView: UITableViewHeaderFooterView, NibDesignable { public override var nibContainerView: UIView { return self.contentView } override public init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.setupNib() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } } open class NibDesignableControl: UIControl, NibDesignable { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib() } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } } open class NibDesignableCollectionReusableView: UICollectionReusableView, NibDesignable { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib() } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } } open class NibDesignableCollectionViewCell: UICollectionViewCell, NibDesignable { public override var nibContainerView: UIView { return self.contentView } // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib() } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } }
mit
998cc5aae1b279da72a829f6a9125151
25.534247
112
0.653846
4.718636
false
false
false
false
urbn/URBNMrkDwn
Sources/URBNMrkDwn/Renderers.swift
1
2111
// // Renderers.swift // Pods // // Created by Jason Grandelli on 10/24/16. // // import Foundation import URBNcmark public struct MrkDwnRenderers { /** Converts a Markdown string to an AST. - parameter markdown: String containing Markdown - parameter options: `MrkDwnOptions` defaults to `MrkDwnOptions.default`. Options for rendering markdown to AST. - throws: `MrkDwnRenderErrors.toASTError` - returns: An OpaquePointer for the AST */ public static func renderASTFromMarkdown(_ markdown: String, options: MrkDwnOptions = .default) throws -> OpaquePointer { guard let node = cmark_parse_document(markdown, markdown.utf8.count, options.rawValue) else { throw MrkDwnRenderErrors.toASTError } return node } /** Converts an AST to HTML. - parameter ast: OpaquePoint to an AST - parameter options: `MrkDwnOptions` defaults to `MrkDwnOptions.default`. Options for rendering markdown to AST & HTML. - throws: `MrkDwnRenderErrors` - returns: An HTML String */ public static func renderHTMLFromAST(_ ast: OpaquePointer, options: MrkDwnOptions = .default) throws -> String { guard let cString = cmark_render_html(ast, options.rawValue) else { throw MrkDwnRenderErrors.astRenderingError } defer { free(cString) } return String(cString: cString) } /** Converts a Markdown string to an AST. - parameter markdown: String containing Markdown - parameter options: `MrkDwnOptions` defaults to `MrkDwnOptions.default`. Options for rendering markdown to HTML. - throws: `MrkDwnRenderErrors.markdownToHTMLError` - returns: An HTML String */ public static func renderHTMLFromMarkdown(_ markdown: String, options: MrkDwnOptions = .default) throws -> String { guard let html = cmark_markdown_to_html(markdown, markdown.utf8.count, options.rawValue) else { throw MrkDwnRenderErrors.markdownToHTMLError } return String(cString: html) } }
mit
d18065224a646c3cee3de61016434f45
31.984375
150
0.669351
4.273279
false
false
false
false
AgentFeeble/pgoapi
Pods/ProtocolBuffers-Swift/Source/ConcreateExtensionField.swift
2
29419
// Protocol Buffers for Swift // // Copyright 2014 Alexey Khohklov(AlexeyXo). // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation public enum ExtensionType : Int32 { case extensionTypeBool case extensionTypeFixed32 case extensionTypeSFixed32 case extensionTypeFloat case extensionTypeFixed64 case extensionTypeSFixed64 case extensionTypeDouble case extensionTypeInt32 case extensionTypeInt64 case extensionTypeSInt32 case extensionTypeSInt64 case extensionTypeUInt32 case extensionTypeUInt64 case extensionTypeBytes case extensionTypeString case extensionTypeMessage case extensionTypeGroup case extensionTypeEnum } public func ==(lhs:ConcreateExtensionField, rhs:ConcreateExtensionField) -> Bool { return true } final public class ConcreateExtensionField:ExtensionField,Equatable { internal var type:ExtensionType public var fieldNumber:Int32 public var extendedClass:AnyClassType public var messageOrGroupClass:Any.Type var defaultValue:Any var isRepeated:Bool = false var isPacked:Bool var isMessageSetWireFormat:Bool public var nameOfExtension:String { get { return extendedClass.className() } } public init(type:ExtensionType, extendedClass:AnyClassType, fieldNumber:Int32, defaultValue:Any, messageOrGroupClass:Any.Type, isRepeated:Bool, isPacked:Bool, isMessageSetWireFormat:Bool) { self.type = type self.fieldNumber = fieldNumber self.extendedClass = extendedClass self.messageOrGroupClass = messageOrGroupClass self.defaultValue = defaultValue self.isRepeated = isRepeated self.isPacked = isPacked self.isMessageSetWireFormat = isMessageSetWireFormat } public var wireType:WireFormat { get { if (isPacked) { return WireFormat.lengthDelimited } switch type { case .extensionTypeBool: return WireFormat.varint case .extensionTypeFixed32: return WireFormat.fixed32 case .extensionTypeSFixed32: return WireFormat.fixed32 case .extensionTypeFloat: return WireFormat.fixed32 case .extensionTypeFixed64: return WireFormat.fixed64 case .extensionTypeSFixed64: return WireFormat.fixed64 case .extensionTypeDouble: return WireFormat.fixed64 case .extensionTypeInt32: return WireFormat.varint case .extensionTypeInt64: return WireFormat.varint case .extensionTypeSInt32: return WireFormat.varint case .extensionTypeSInt64: return WireFormat.varint case .extensionTypeUInt32: return WireFormat.varint case .extensionTypeUInt64: return WireFormat.varint case .extensionTypeBytes: return WireFormat.lengthDelimited case .extensionTypeString: return WireFormat.lengthDelimited case .extensionTypeMessage: return WireFormat.lengthDelimited case .extensionTypeGroup: return WireFormat.startGroup case .extensionTypeEnum: return WireFormat.varint } } } func typeIsPrimitive(type:ExtensionType) ->Bool { switch type { case .extensionTypeBool, .extensionTypeFixed32, .extensionTypeSFixed32, .extensionTypeFloat, .extensionTypeFixed64, .extensionTypeSFixed64, .extensionTypeDouble, .extensionTypeInt32, .extensionTypeInt64, .extensionTypeSInt32, .extensionTypeSInt64, .extensionTypeUInt32, .extensionTypeUInt64, .extensionTypeBytes, .extensionTypeString, .extensionTypeEnum: return true default: return false } } func typeIsFixedSize(type:ExtensionType) -> Bool { switch (type) { case .extensionTypeBool,.extensionTypeFixed32,.extensionTypeSFixed32,.extensionTypeFloat,.extensionTypeFixed64,.extensionTypeSFixed64,.extensionTypeDouble: return true default: return false } } func typeSize(type:ExtensionType) -> Int32 { switch type { case .extensionTypeBool: return 1 case .extensionTypeFixed32, .extensionTypeSFixed32, .extensionTypeFloat: return 4 case .extensionTypeFixed64,.extensionTypeSFixed64, .extensionTypeDouble: return 8 default: return 0 } } func writeSingleValueIncludingTag(value:Any, output:CodedOutputStream) throws { switch type { case .extensionTypeBool: let downCastValue = value as! Bool try output.writeBool(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeFixed32: let downCastValue = value as! UInt32 try output.writeFixed32(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeSFixed32: let downCastValue = value as! Int32 try output.writeSFixed32(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeFixed64: let downCastValue = value as! UInt64 try output.writeFixed64(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeSFixed64: let downCastValue = value as! Int64 try output.writeSFixed64(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeDouble: let downCastValue = value as! Double try output.writeDouble(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeFloat: let downCastValue = value as! Float try output.writeFloat(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeInt32: let downCastValue = value as! Int32 try output.writeInt32(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeInt64: let downCastValue = value as! Int64 try output.writeInt64(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeSInt32: let downCastValue = value as! Int32 try output.writeSInt32(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeSInt64: let downCastValue = value as! Int64 try output.writeSInt64(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeUInt32: let downCastValue = value as! UInt32 try output.writeUInt32(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeUInt64: let downCastValue = value as! UInt64 try output.writeUInt64(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeBytes: let downCastValue = value as! Data try output.writeData(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeString: let downCastValue = value as! String try output.writeString(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeEnum: let downCastValue = value as! Int32 try output.writeEnum(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeGroup: let downCastValue = value as! GeneratedMessage try output.writeGroup(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeMessage where isMessageSetWireFormat == true: let downCastValue = value as! GeneratedMessage try output.writeMessageSetExtension(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeMessage where isMessageSetWireFormat == false: let downCastValue = value as! GeneratedMessage try output.writeMessage(fieldNumber: fieldNumber, value:downCastValue) default: throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Extensions Type") } } func writeSingleValueNoTag(value:Any, output:CodedOutputStream) throws { switch type { case .extensionTypeBool: let downCastValue = value as! Bool try output.writeBoolNoTag(value: downCastValue) case .extensionTypeFixed32: let downCastValue = value as! UInt32 try output.writeFixed32NoTag(value: downCastValue) case .extensionTypeSFixed32: let downCastValue = value as! Int32 try output.writeSFixed32NoTag(value: downCastValue) case .extensionTypeInt32: let downCastValue = value as! Int32 try output.writeInt32NoTag(value: downCastValue) case .extensionTypeSInt32: let downCastValue = value as! Int32 try output.writeSInt32NoTag(value: downCastValue) case .extensionTypeEnum: let downCastValue = value as! Int32 try output.writeEnumNoTag(value: downCastValue) case .extensionTypeFixed64: let downCastValue = value as! UInt64 try output.writeFixed64NoTag(value: downCastValue) case .extensionTypeInt64: let downCastValue = value as! Int64 try output.writeInt64NoTag(value: downCastValue) case .extensionTypeSInt64: let downCastValue = value as! Int64 try output.writeSInt64NoTag(value: downCastValue) case .extensionTypeSFixed64: let downCastValue = value as! Int64 try output.writeSFixed64NoTag(value: downCastValue) case .extensionTypeDouble: let downCastValue = value as! Double try output.writeDoubleNoTag(value: downCastValue) case .extensionTypeFloat: let downCastValue = value as! Float try output.writeFloatNoTag(value: downCastValue) case .extensionTypeUInt32: let downCastValue = value as! UInt32 try output.writeUInt32NoTag(value: downCastValue) case .extensionTypeUInt64: let downCastValue = value as! UInt64 try output.writeUInt64NoTag(value: downCastValue) case .extensionTypeBytes: let downCastValue = value as! Data try output.writeDataNoTag(data: downCastValue) case .extensionTypeString: let downCastValue = value as! String try output.writeStringNoTag(value: downCastValue) case .extensionTypeGroup: let downCastValue = value as! GeneratedMessage try output.writeGroupNoTag(fieldNumber: fieldNumber, value:downCastValue) case .extensionTypeMessage: let downCastValue = value as! GeneratedMessage try output.writeMessageNoTag(value: downCastValue) } } func computeSingleSerializedSizeIncludingTag(value:Any) -> Int32 { switch type { case .extensionTypeFixed32: let downCastValue = value as! UInt32 return downCastValue.computeFixed32Size(fieldNumber: fieldNumber) case .extensionTypeSFixed32: let downCastValue = value as! Int32 return downCastValue.computeSFixed32Size(fieldNumber: fieldNumber) case .extensionTypeSInt32: let downCastValue = value as! Int32 return downCastValue.computeSInt32Size(fieldNumber: fieldNumber) case .extensionTypeInt32: let downCastValue = value as! Int32 return downCastValue.computeInt32Size(fieldNumber: fieldNumber) case .extensionTypeEnum: let downCastValue = value as! Int32 return downCastValue.computeEnumSize(fieldNumber: fieldNumber) case .extensionTypeFixed64: let downCastValue = value as! UInt64 return downCastValue.computeFixed64Size(fieldNumber: fieldNumber) case .extensionTypeSFixed64: let downCastValue = value as! Int64 return downCastValue.computeSFixed64Size(fieldNumber: fieldNumber) case .extensionTypeInt64: let downCastValue = value as! Int64 return downCastValue.computeInt64Size(fieldNumber: fieldNumber) case .extensionTypeSInt64: let downCastValue = value as! Int64 return downCastValue.computeSInt64Size(fieldNumber: fieldNumber) case .extensionTypeFloat: let downCastValue = value as! Float return downCastValue.computeFloatSize(fieldNumber: fieldNumber) case .extensionTypeDouble: let downCastValue = value as! Double return downCastValue.computeDoubleSize(fieldNumber: fieldNumber) case .extensionTypeUInt32: let downCastValue = value as! UInt32 return downCastValue.computeUInt32Size(fieldNumber: fieldNumber) case .extensionTypeUInt64: let downCastValue = value as! UInt64 return downCastValue.computeUInt64Size(fieldNumber: fieldNumber) case .extensionTypeBytes: let downCastValue = value as! Data return downCastValue.computeDataSize(fieldNumber: fieldNumber) case .extensionTypeString: let downCastValue = value as! String return downCastValue.computeStringSize(fieldNumber: fieldNumber) case .extensionTypeGroup: let downCastValue = value as! GeneratedMessage return downCastValue.computeGroupSize(fieldNumber: fieldNumber) case .extensionTypeMessage where isMessageSetWireFormat == true: let downCastValue = value as! GeneratedMessage return downCastValue.computeMessageSetExtensionSize(fieldNumber: fieldNumber) case .extensionTypeMessage where isMessageSetWireFormat == false: let downCastValue = value as! GeneratedMessage return downCastValue.computeMessageSize(fieldNumber: fieldNumber) case .extensionTypeBool: let downCastValue = value as! Bool return downCastValue.computeBoolSize(fieldNumber: fieldNumber) default: return 0 } } func computeSingleSerializedSizeNoTag(value:Any) -> Int32 { switch type { case .extensionTypeBool: let downCastValue = value as! Bool return downCastValue.computeBoolSizeNoTag() case .extensionTypeFixed32: let downCastValue = value as! UInt32 return downCastValue.computeFixed32SizeNoTag() case .extensionTypeSFixed32: let downCastValue = value as! Int32 return downCastValue.computeSFixed32SizeNoTag() case .extensionTypeInt32: let downCastValue = value as! Int32 return downCastValue.computeInt32SizeNoTag() case .extensionTypeSInt32: let downCastValue = value as! Int32 return downCastValue.computeSInt32SizeNoTag() case .extensionTypeEnum: let downCastValue = value as! Int32 return downCastValue.computeEnumSizeNoTag() case .extensionTypeFixed64: let downCastValue = value as! UInt64 return downCastValue.computeFixed64SizeNoTag() case .extensionTypeSFixed64: let downCastValue = value as! Int64 return downCastValue.computeSFixed64SizeNoTag() case .extensionTypeInt64: let downCastValue = value as! Int64 return downCastValue.computeInt64SizeNoTag() case .extensionTypeSInt64: let downCastValue = value as! Int64 return downCastValue.computeSInt64SizeNoTag() case .extensionTypeFloat: let downCastValue = value as! Float return downCastValue.computeFloatSizeNoTag() case .extensionTypeDouble: let downCastValue = value as! Double return downCastValue.computeDoubleSizeNoTag() case .extensionTypeUInt32: let downCastValue = value as! UInt32 return downCastValue.computeUInt32SizeNoTag() case .extensionTypeUInt64: let downCastValue = value as! UInt64 return downCastValue.computeUInt64SizeNoTag() case .extensionTypeBytes: let downCastValue = value as! Data return downCastValue.computeDataSizeNoTag() case .extensionTypeString: let downCastValue = value as! String return downCastValue.computeStringSizeNoTag() case .extensionTypeGroup: let downCastValue = value as! GeneratedMessage return downCastValue.computeGroupSizeNoTag() case .extensionTypeMessage: let downCastValue = value as! GeneratedMessage return downCastValue.computeMessageSizeNoTag() } } func writeDescriptionOfSingleValue(value:Any, indent:String) throws -> String { var output = "" if typeIsPrimitive(type: type) { output += "\(indent)\(value)\n" } else if let values = value as? GeneratedMessage { output += try values.getDescription(indent: indent) } else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Extensions Type") } return output } func writeRepeatedValuesIncludingTags<T>(values:Array<T>, output:CodedOutputStream) throws { if (isPacked) { try output.writeTag(fieldNumber: fieldNumber, format: WireFormat.lengthDelimited) var dataSize:Int32 = 0 if (typeIsFixedSize(type: type)) { dataSize = Int32(values.count) * typeSize(type: type) } else { for value in values { dataSize += computeSingleSerializedSizeNoTag(value: value) } } try output.writeRawVarint32(value: dataSize) for value in values { try writeSingleValueNoTag(value: value, output: output) } } else { for value in values { try writeSingleValueIncludingTag(value: value, output: output) } } } func computeRepeatedSerializedSizeIncludingTags<T>(values:Array<T>) -> Int32 { if (isPacked) { var size:Int32 = 0 if (typeIsFixedSize(type: type)) { size = Int32(values.count) * typeSize(type: type) } else { for value in values { size += computeSingleSerializedSizeNoTag(value: value) } } return size + fieldNumber.computeTagSize() + size.computeRawVarint32Size() } else { var size:Int32 = 0 for value in values { size += computeSingleSerializedSizeIncludingTag(value: value) } return size } } public func computeSerializedSizeIncludingTag(value:Any) -> Int32 { if isRepeated { switch value { case let values as [Int32]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [Int64]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [UInt64]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [UInt32]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [Float]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [Double]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [Bool]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [String]: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as Array<Data>: return computeRepeatedSerializedSizeIncludingTags(values: values) case let values as [GeneratedMessage]: return computeRepeatedSerializedSizeIncludingTags(values: values) default: return 0 } } else { return computeSingleSerializedSizeIncludingTag(value: value) } } public func writeValueIncludingTagToCodedOutputStream(value:Any, output:CodedOutputStream) throws { if isRepeated { switch value { case let values as [Int32]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [Int64]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [UInt64]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [UInt32]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [Bool]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [Float]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [Double]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [String]: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as Array<Data>: try writeRepeatedValuesIncludingTags(values: values, output:output) case let values as [GeneratedMessage]: try writeRepeatedValuesIncludingTags(values: values, output:output) default: break } } else { try writeSingleValueIncludingTag(value: value, output:output) } } private func iterationRepetedValuesForDescription<T>(values:Array<T>, indent:String) throws -> String { var output = "" for singleValue in values { output += try writeDescriptionOfSingleValue(value: singleValue, indent: indent) } return output } public func getDescription(value:Any, indent:String) throws -> String { var output = "" if isRepeated { switch value { case let values as [Int32]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [Int64]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [UInt64]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [UInt32]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [Bool]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [Float]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [Double]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [String]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as Array<Data>: output += try iterationRepetedValuesForDescription(values: values, indent: indent) case let values as [GeneratedMessage]: output += try iterationRepetedValuesForDescription(values: values, indent: indent) default: break } } else { output += try writeDescriptionOfSingleValue(value: value, indent:indent) } return output } func mergeMessageSetExtentionFromCodedInputStream(input:CodedInputStream, unknownFields:UnknownFieldSet.Builder) throws { throw ProtocolBuffersError.illegalState("Method Not Supported") } func readSingleValueFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Any { switch type { case .extensionTypeBool: return try input.readBool() case .extensionTypeFixed32: return try input.readFixed32() case .extensionTypeSFixed32: return try input.readSFixed32() case .extensionTypeFixed64: return try input.readFixed64() case .extensionTypeSFixed64: return try input.readSFixed64() case .extensionTypeFloat: return try input.readFloat() case .extensionTypeDouble: return try input.readDouble() case .extensionTypeInt32: return try input.readInt32() case .extensionTypeInt64: return try input.readInt64() case .extensionTypeSInt32: return try input.readSInt32() case .extensionTypeSInt64: return try input.readSInt64() case .extensionTypeUInt32: return try input.readUInt32() case .extensionTypeUInt64: return try input.readUInt64() case .extensionTypeBytes: return try input.readData() case .extensionTypeString: return try input.readString() case .extensionTypeEnum: return try input.readEnum() case .extensionTypeGroup: if let mg = messageOrGroupClass as? GeneratedMessage.Type { let buider = mg.classBuilder() try input.readGroup(fieldNumber: Int(fieldNumber), builder: buider, extensionRegistry: extensionRegistry) let mes = try buider.build() return mes } case .extensionTypeMessage: if let mg = messageOrGroupClass as? GeneratedMessage.Type { let buider = mg.classBuilder() try input.readMessage(builder: buider, extensionRegistry: extensionRegistry) let mes = try buider.build() return mes } } return "" } public func mergeFrom(codedInputStream:CodedInputStream, unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, builder:ExtendableMessageBuilder, tag:Int32) throws { if (isPacked) { let length:Int32 = try codedInputStream.readRawVarint32() let limit = Int(try codedInputStream.pushLimit(byteLimit: Int(length))) while (codedInputStream.bytesUntilLimit() > 0) { let value = try readSingleValueFromCodedInputStream(input: codedInputStream, extensionRegistry:extensionRegistry) _ = try builder.addExtension(extensions: self, value:value) } codedInputStream.popLimit(oldLimit: Int(limit)) } else if isMessageSetWireFormat { try mergeMessageSetExtentionFromCodedInputStream(input: codedInputStream, unknownFields:unknownFields) } else { let value = try readSingleValueFromCodedInputStream(input: codedInputStream, extensionRegistry:extensionRegistry) if (isRepeated) { _ = try builder.addExtension(extensions: self, value:value) } else { _ = try builder.setExtension(extensions: self, value:value) } } } }
apache-2.0
a809fec641a49f6355f02136e5a3c4c4
37.607612
362
0.622557
5.563351
false
false
false
false
eBardX/XestiMonitors
Tests/Mock/MockLocationManager.swift
1
16308
// // MockLocationManager.swift // XestiMonitorsTests // // Created by J. G. Pusey on 2018-03-22. // // © 2018 J. G. Pusey (see LICENSE.md) // import CoreLocation @testable import XestiMonitors // swiftlint:disable file_length type_body_length internal class MockLocationManager: LocationManagerProtocol { static func deferredLocationUpdatesAvailable() -> Bool { return mockDeferredLocationUpdatesAvailable } #if os(iOS) static func headingAvailable() -> Bool { return mockHeadingAvailable } #endif static func authorizationStatus() -> CLAuthorizationStatus { return mockAuthorizationStatus } #if os(iOS) || os(macOS) static func isMonitoringAvailable(for regionClass: AnyClass) -> Bool { if regionClass is CLRegion.Type { return mockRegionAvailable } else { return false } } #endif #if os(iOS) static func isRangingAvailable() -> Bool { return mockBeaconRangingAvailable } #endif static func locationServicesEnabled() -> Bool { return mockLocationServicesEnabled } #if os(iOS) || os(macOS) static func significantLocationChangeMonitoringAvailable() -> Bool { return mockSignificantLocationAvailable } #endif init() { #if os(iOS) || os(watchOS) self.activityType = .other #endif #if os(iOS) || os(watchOS) self.allowsBackgroundLocationUpdates = false #endif self.desiredAccuracy = kCLLocationAccuracyBest self.distanceFilter = kCLDistanceFilterNone #if os(iOS) self.heading = nil #endif #if os(iOS) self.headingFilter = 1 #endif #if os(iOS) self.headingOrientation = .portrait #endif self.location = nil #if os(iOS) || os(macOS) self.maximumRegionMonitoringDistance = 1_000 #endif self.mockAlwaysAuthorizationRequested = false self.mockLocationUpdatesDeferred = false self.mockHeadingCalibrationDisplayVisible = false self.mockHeadingRunning = false self.mockLocationRequested = false self.mockRegionStateRequested = nil self.mockSignificantLocationRunning = false self.mockStandardLocationRunning = false self.mockVisitRunning = false self.mockWhenInUseAuthorizationRequested = false #if os(iOS) || os(macOS) self.monitoredRegions = [] #endif #if os(iOS) self.pausesLocationUpdatesAutomatically = false #endif #if os(iOS) self.rangedRegions = [] #endif #if os(iOS) self.showsBackgroundLocationIndicator = false #endif } #if os(iOS) || os(watchOS) @available(watchOS 4.0, *) var activityType: CLActivityType #endif #if os(iOS) || os(watchOS) @available(watchOS 4.0, *) var allowsBackgroundLocationUpdates: Bool #endif weak var delegate: CLLocationManagerDelegate? var desiredAccuracy: CLLocationAccuracy var distanceFilter: CLLocationDistance #if os(iOS) var heading: CLHeading? #endif #if os(iOS) var headingFilter: CLLocationDegrees #endif #if os(iOS) var headingOrientation: CLDeviceOrientation #endif var location: CLLocation? #if os(iOS) || os(macOS) private(set) var maximumRegionMonitoringDistance: CLLocationDistance #endif #if os(iOS) || os(macOS) private(set) var monitoredRegions: Set<CLRegion> #endif #if os(iOS) var pausesLocationUpdatesAutomatically: Bool #endif #if os(iOS) private(set) var rangedRegions: Set<CLRegion> #endif #if os(iOS) var showsBackgroundLocationIndicator: Bool #endif #if os(iOS) func allowDeferredLocationUpdates(untilTraveled distance: CLLocationDistance, timeout: TimeInterval) { mockLocationUpdatesDeferred = true } #endif #if os(iOS) func disallowDeferredLocationUpdates() { mockLocationUpdatesDeferred = false } #endif #if os(iOS) func dismissHeadingCalibrationDisplay() { mockHeadingCalibrationDisplayVisible = false } #endif #if os(iOS) || os(watchOS) func requestAlwaysAuthorization() { mockAlwaysAuthorizationRequested = true } #endif #if os(iOS) || os(tvOS) || os(watchOS) func requestLocation() { mockLocationRequested = true } #endif #if os(iOS) || os(macOS) func requestState(for region: CLRegion) { mockRegionStateRequested = region } #endif #if os(iOS) || os(tvOS) || os(watchOS) func requestWhenInUseAuthorization() { mockWhenInUseAuthorizationRequested = true } #endif #if os(iOS) || os(macOS) func startMonitoring(for region: CLRegion) { monitoredRegions.insert(region) } #endif #if os(iOS) || os(macOS) func startMonitoringSignificantLocationChanges() { mockSignificantLocationRunning = true } #endif #if os(iOS) func startMonitoringVisits() { mockVisitRunning = true } #endif #if os(iOS) func startRangingBeacons(in region: CLBeaconRegion) { rangedRegions.insert(region) } #endif #if os(iOS) func startUpdatingHeading() { mockHeadingRunning = true } #endif #if os(iOS) || os(macOS) || os(watchOS) @available(watchOS 3.0, *) func startUpdatingLocation() { mockStandardLocationRunning = true } #endif #if os(iOS) || os(macOS) func stopMonitoring(for region: CLRegion) { monitoredRegions.remove(region) } #endif #if os(iOS) || os(macOS) func stopMonitoringSignificantLocationChanges() { mockSignificantLocationRunning = false } #endif #if os(iOS) func stopMonitoringVisits() { mockVisitRunning = false } #endif #if os(iOS) func stopRangingBeacons(in region: CLBeaconRegion) { rangedRegions.remove(region) } #endif #if os(iOS) func stopUpdatingHeading() { mockHeadingRunning = false } #endif func stopUpdatingLocation() { mockStandardLocationRunning = false } private static var mockAuthorizationStatus = CLAuthorizationStatus.notDetermined private static var mockDeferredLocationUpdatesAvailable = false private static var mockBeaconRangingAvailable = false private static var mockHeadingAvailable = false private static var mockLocationServicesEnabled = false private static var mockRegionAvailable = false private static var mockSignificantLocationAvailable = false private var mockAlwaysAuthorizationRequested: Bool private var mockHeadingCalibrationDisplayVisible: Bool private var mockHeadingRunning: Bool private var mockLocationRequested: Bool private var mockLocationUpdatesDeferred: Bool private var mockRegionStateRequested: CLRegion? private var mockSignificantLocationRunning: Bool private var mockStandardLocationRunning: Bool private var mockVisitRunning: Bool private var mockWhenInUseAuthorizationRequested: Bool private var locationManager: CLLocationManager { return unsafeBitCast(self, to: CLLocationManager.self) } // MARK: - #if os(iOS) var isHeadingCalibrationDisplayVisible: Bool { return mockHeadingCalibrationDisplayVisible } #endif #if os(iOS) var isLocationUpdatesDeferred: Bool { return mockLocationUpdatesDeferred } #endif #if os(iOS) func hideHeadingCalibrationDisplay() { mockHeadingCalibrationDisplayVisible = false } #endif #if os(iOS) func pauseStandardLocationUpdates() { guard mockStandardLocationRunning else { return } delegate?.locationManagerDidPauseLocationUpdates?(locationManager) } #endif #if os(iOS) func resumeStandardLocationUpdates() { guard mockStandardLocationRunning else { return } delegate?.locationManagerDidResumeLocationUpdates?(locationManager) } #endif #if os(iOS) func showHeadingCalibrationDisplay() { mockHeadingCalibrationDisplayVisible = delegate?.locationManagerShouldDisplayHeadingCalibration?(locationManager) ?? false } #endif func updateAuthorization(error: Error) { guard mockAlwaysAuthorizationRequested || mockWhenInUseAuthorizationRequested else { return } mockAlwaysAuthorizationRequested = false mockWhenInUseAuthorizationRequested = false delegate?.locationManager?(locationManager, didFailWithError: error) } func updateAuthorization(forceStatus: CLAuthorizationStatus) { type(of: self).mockAuthorizationStatus = forceStatus } func updateAuthorization(status: CLAuthorizationStatus) { guard mockAlwaysAuthorizationRequested || mockWhenInUseAuthorizationRequested else { return } mockAlwaysAuthorizationRequested = false mockWhenInUseAuthorizationRequested = false type(of: self).mockAuthorizationStatus = status delegate?.locationManager?(locationManager, didChangeAuthorization: status) } #if os(iOS) func updateBeaconRanging(available: Bool) { type(of: self).mockBeaconRangingAvailable = available } #endif #if os(iOS) func updateBeaconRanging(error: Error) { guard !rangedRegions.isEmpty else { return } delegate?.locationManager?(locationManager, didFailWithError: error) } #endif #if os(iOS) func updateBeaconRanging(error: Error, for region: CLBeaconRegion) { guard rangedRegions.contains(region) else { return } delegate?.locationManager?(locationManager, rangingBeaconsDidFailFor: region, withError: error) } #endif #if os(iOS) func updateBeaconRanging(beacons: [CLBeacon], in region: CLBeaconRegion) { guard rangedRegions.contains(region) else { return } delegate?.locationManager?(locationManager, didRangeBeacons: beacons, in: region) } #endif #if os(iOS) func updateHeading(_ heading: CLHeading) { guard mockHeadingRunning else { return } delegate?.locationManager?(locationManager, didUpdateHeading: heading) } #endif #if os(iOS) func updateHeading(available: Bool) { type(of: self).mockHeadingAvailable = available } #endif #if os(iOS) func updateHeading(error: Error) { guard mockHeadingRunning else { return } delegate?.locationManager?(locationManager, didFailWithError: error) } #endif #if os(iOS) func updateHeading(forceHeading: CLHeading?) { heading = forceHeading } #endif func updateLocationServices(enabled: Bool) { type(of: self).mockLocationServicesEnabled = enabled } #if os(iOS) || os(macOS) func updateRegion(_ region: CLRegion?, error: Error) { if let region = region { guard monitoredRegions.contains(region) else { return } } delegate?.locationManager?(locationManager, monitoringDidFailFor: region, withError: error) } #endif #if os(iOS) || os(macOS) func updateRegion(available: Bool) { type(of: self).mockRegionAvailable = available } #endif #if os(iOS) || os(macOS) func updateRegion(enter region: CLRegion) { guard monitoredRegions.contains(region) else { return } delegate?.locationManager?(locationManager, didEnterRegion: region) } #endif #if os(iOS) || os(macOS) func updateRegion(error: Error) { guard !monitoredRegions.isEmpty else { return } delegate?.locationManager?(locationManager, didFailWithError: error) } #endif #if os(iOS) || os(macOS) func updateRegion(exit region: CLRegion) { guard monitoredRegions.contains(region) else { return } delegate?.locationManager?(locationManager, didExitRegion: region) } #endif #if os(iOS) || os(macOS) func updateRegion(state: CLRegionState) { guard let region = mockRegionStateRequested else { return } delegate?.locationManager?(locationManager, didDetermineState: state, for: region) } #endif #if os(iOS) || os(macOS) func updateRegion(start region: CLRegion) { guard monitoredRegions.contains(region) else { return } delegate?.locationManager?(locationManager, didStartMonitoringFor: region) } #endif #if os(iOS) || os(macOS) func updateSignificantLocation(_ location: CLLocation) { guard mockSignificantLocationRunning else { return } delegate?.locationManager?(locationManager, didUpdateLocations: [location]) } #endif #if os(iOS) || os(macOS) func updateSignificantLocation(available: Bool) { type(of: self).mockSignificantLocationAvailable = available } #endif #if os(iOS) || os(macOS) func updateSignificantLocation(error: Error) { guard mockSignificantLocationRunning else { return } delegate?.locationManager?(locationManager, didFailWithError: error) } #endif func updateStandardLocation(_ location: CLLocation) { guard mockLocationRequested || mockStandardLocationRunning else { return } mockLocationRequested = false delegate?.locationManager?(locationManager, didUpdateLocations: [location]) } #if os(iOS) || os(macOS) func updateStandardLocation(canDeferUpdates: Bool) { type(of: self).mockDeferredLocationUpdatesAvailable = canDeferUpdates } #endif #if os(iOS) || os(macOS) func updateStandardLocation(deferredError: Error?) { guard mockStandardLocationRunning else { return } delegate?.locationManager?(locationManager, didFinishDeferredUpdatesWithError: deferredError) } #endif func updateStandardLocation(error: Error) { guard mockStandardLocationRunning else { return } delegate?.locationManager?(locationManager, didFailWithError: error) } func updateStandardLocation(forceLocation: CLLocation?) { location = forceLocation } #if os(iOS) func updateVisit(_ visit: CLVisit) { guard mockVisitRunning else { return } delegate?.locationManager?(locationManager, didVisit: visit) } #endif #if os(iOS) func updateVisit(error: Error) { guard mockVisitRunning else { return } delegate?.locationManager?(locationManager, didFailWithError: error) } #endif } // swiftlint:enable file_length type_body_length
mit
be399e20cf107ee56062c599f1c313b0
25.344103
130
0.605691
5.20824
false
false
false
false
Stitch7/Instapod
Instapod/Podcast/TableView/PodcastsTableViewController.swift
1
11248
// // PodcastsTableViewController.swift // Instapod // // Created by Christopher Reitz on 18.02.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit import CoreData class PodcastsTableViewController: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating, CoreDataContextInjectable, FeedUpdaterDelegate { // MARK: - Properties var detailViewController: EpisodesViewController? var delegate: PodcastListDelegate? var searchController: UISearchController! var podcasts = [Podcast]() var filteredData = [Podcast]() let refreshControlTitle = "Pull to refresh …" // TODO: i18n let podcastCountLabel = UILabel() // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = ColorPalette.Background edgesForExtendedLayout = UIRectEdge() automaticallyAdjustsScrollViewInsets = false configureSplitViewController() configureTableView() configureRefreshControl() configureSearchBar() configureToolBar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Workaround for clearsSelectionOnViewWillAppear still buggy on gesture // clearsSelectionOnViewWillAppear = splitViewController!.collapsed if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: false) } // navigationController?.view.tintColor = ColorPalette.Main navigationController?.navigationBar.barTintColor = ColorPalette.Main if let appDelegate = UIApplication.shared.delegate, let window = appDelegate.window { window!.tintColor = ColorPalette.Main } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.async { guard let refreshControl = self.refreshControl else { return } refreshControl.beginRefreshing() refreshControl.endRefreshing() } } func configureSplitViewController() { guard let splitVC = self.splitViewController else { return } let controllers = splitVC.viewControllers if let nc = controllers[controllers.count - 1] as? UINavigationController { detailViewController = nc.topViewController as? EpisodesViewController } } func configureTableView() { tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) tableView.scrollIndicatorInsets = tableView.contentInset tableView.register(UINib(nibName: "PodcastTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell") tableView.backgroundColor = ColorPalette.TableView.Background tableView.backgroundView = UIView() } func configureRefreshControl() { let refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: refreshControlTitle) refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged) self.refreshControl = refreshControl tableView.addSubview(refreshControl) tableView.sendSubview(toBack: refreshControl) } func configureSearchBar() { definesPresentationContext = true searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.hidesNavigationBarDuringPresentation = false searchController.dimsBackgroundDuringPresentation = false // searchController.searchBar.tintColor = UIColor.blackColor() // searchController.searchBar.placeholder = "Search" searchController.searchBar.backgroundColor = ColorPalette.TableView.Background searchController.searchBar.barTintColor = ColorPalette.TableView.Background searchController.searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default) searchController.searchBar.searchBarStyle = .minimal searchController.searchBar.sizeToFit() tableView.tableHeaderView = searchController.searchBar tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.height) } func configureToolBar() { // navigationController?.toolbarHidden = false // // podcastCountLabel.text = "\(podcasts.count) Subscriptions" // TODO: i18n // podcastCountLabel.sizeToFit() // // navigationController?.toolbar.addSubview(podcastCountLabel) } // MARK: - Actions func handleRefresh(_ refreshControl: UIRefreshControl) { refreshControl.attributedTitle = NSAttributedString(string: "Searching for new episodes …") // TODO: i18n delegate?.updateFeeds() } func updateSortIndizes() { guard let coordinator = coreDataContext.persistentStoreCoordinator else { return } do { for (index, podcast) in podcasts.enumerated() { guard let id = podcast.id, let objectID = coordinator.managedObjectID(forURIRepresentation: id as URL), let managedPodcast = try coreDataContext.existingObject(with: objectID) as? PodcastManagedObject else { continue } managedPodcast.sortIndex = index as NSNumber? } try coreDataContext.save() } catch { print("Can't find podcast to delete \(error)") } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 67.0 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.0 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0 } override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "Unsubscribe" // TODO: i18n } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let podcast = podcasts[(indexPath as NSIndexPath).row] self.delegate?.podcastSelected(podcast) } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { if self.tableView.isEditing { return .delete } return .none } // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = podcasts.count podcastCountLabel.text = "\(count) Subscriptions" // TODO: i18n return count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PodcastTableViewCell let podcast = podcasts[(indexPath as NSIndexPath).row] var image: UIImage? if let thumbnailData = podcast.image?.thumbnail56 { image = UIImage(data: thumbnailData as Data) } else { image = UIImage(named: "defaultLogo56") } cell.logoImageView?.image = image cell.titleLabel!.text = podcast.title cell.authorLabel!.text = podcast.author let episodesCount = podcast.episodes?.count ?? 0 cell.unheardEpisodesLabel!.text = "\(episodesCount) Episodes" // TODO: i18n let separatorLineView = UIView(frame: CGRect(x: 0.0, y: cell.bounds.size.height - 1.0, width: cell.bounds.size.width, height: 0.5)) separatorLineView.backgroundColor = ColorPalette.TableView.Cell.SeparatorLine cell.contentView.addSubview(separatorLineView) return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) { let itemToMove = podcasts[(fromIndexPath as NSIndexPath).row] podcasts.remove(at: (fromIndexPath as NSIndexPath).row) podcasts.insert(itemToMove, at: (toIndexPath as NSIndexPath).row) updateSortIndizes() } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else { return } let deleted = podcasts.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async(execute: { let context = self.coreDataContext guard let id = deleted.id, let coordinator = context.persistentStoreCoordinator, let objectID = coordinator.managedObjectID(forURIRepresentation: id as URL) else { return } do { let objectToDelete = try context.existingObject(with: objectID) context.delete(objectToDelete) try context.save() } catch { print("Can't find podcast to delete \(error)") } }) } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchController.searchBar.setShowsCancelButton(false, animated: false) } // MARK: - UISearchResultsUpdating func updateSearchResults(for searchController: UISearchController) { // let searchText = searchController.searchBar.text!.trimmingCharacters(in: .whitespaces()) let searchText = searchController.searchBar.text print(searchText) // filteredBoxes = boxes.filter({ ( box: Box) -> Bool in // let match = box.name.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch) // return match != nil // }) tableView.reloadData() } // MARK: - FeedUpdaterDelegate func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithEpisode foundEpisode: Episode, ofPodcast podcast: Podcast) { if let refreshControl = refreshControl, let feedTitle = podcast.title, let episodeTitle = foundEpisode.title { refreshControl.attributedTitle = NSAttributedString(string: "Found \(feedTitle) - \(episodeTitle)") // TODO: i18n } } func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithNumberOfEpisodes numberOfEpisodes: Int) { tableView.reloadData() tableView.layoutIfNeeded() if let refreshControl = refreshControl { refreshControl.endRefreshing() refreshControl.attributedTitle = NSAttributedString(string: refreshControlTitle) } } }
mit
7ec6cd1d824d3604a47679d60d546a1d
37.372014
152
0.676065
5.655433
false
false
false
false
ubi-naist/SenStick
ios/Pods/iOSDFULibrary/iOSDFULibrary/Classes/Utilities/crc32.swift
10
6638
// // crc32.swift // SuperSFV // // Created by C.W. Betts on 8/23/15. // // /* crc32.swift -- compute the CRC-32 of a data stream Copyright (C) 1995-1998 Mark Adler Copyright (C) 2015 C.W. "Madd the Sane" Betts This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler [email protected] [email protected] */ import Foundation /** Table of CRC-32's of all single-byte values (made by make_crc_table) */ private let crcTable: [UInt32] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d] func crc32(_ crc: UInt32, data: Data?) -> UInt32 { guard let data = data else { return crc32(0, buffer: nil, length: 0) } return crc32(crc, buffer: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), length: data.count) } /** Update a running crc with the bytes buf[0..len-1] and return the updated crc. If buf is `nil`, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application.<br> Usage example: Var crc: UInt32 = crc32(0, nil, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer: buffer, length: length) } if (crc != original_crc) error(); */ func crc32(_ crc: UInt32, buffer: UnsafePointer<UInt8>?, length: Int) -> UInt32 { if buffer == nil { return 0 } var crc1 = crc ^ 0xffffffff var len = length var buf = buffer func DO1() { let toBuf = buf?.pointee buf = buf! + 1 crc1 = crcTable[Int((crc1 ^ UInt32(toBuf!)) & 0xFF)] ^ crc1 >> 8 } func DO2() { DO1(); DO1(); } func DO4() { DO2(); DO2(); } func DO8() { DO4(); DO4(); } while len >= 8 { DO8() len -= 8 } if len != 0 { repeat { len -= 1 DO1() } while len != 0 } return crc1 ^ 0xffffffff; } func ==(lhs: CRC32, rhs: CRC32) -> Bool { return lhs.initialized == rhs.initialized && lhs.crc == rhs.crc } final class CRC32: Hashable { fileprivate var initialized = false fileprivate(set) var crc: UInt32 = 0 var hashValue: Int { return Int(crc) } init() {} convenience init(data: Data) { self.init() crc = crc32(crc, data: data) initialized = true } func run(buffer: UnsafePointer<UInt8>, length: Int) { crc = crc32(crc, buffer: buffer, length: length) initialized = true } func run(data: Data) { crc = crc32(crc, data: data) initialized = true } }
mit
5358d1051c2acc0326f2b3b9c48a00b7
38.987952
122
0.706237
2.27875
false
false
false
false
Ramotion/expanding-collection
Source/ExpandingViewController/CollectionView/Cells/BasePageCollectionCell.swift
1
11229
// // PageConllectionCell.swift // TestCollectionView // // Created by Alex K. on 04/05/16. // Copyright © 2016 Alex K. All rights reserved. // import UIKit /// Base class for UICollectionViewCell open class BasePageCollectionCell: UICollectionViewCell { /// DEPRECATED! Animation oposition offset when cell is open @IBInspectable open var yOffset: CGFloat = 40 /// Spacing between centers of views @IBInspectable open var ySpacing: CGFloat = CGFloat.greatestFiniteMagnitude /// Additional height of back view, when it grows @IBInspectable open var additionalHeight: CGFloat = CGFloat.greatestFiniteMagnitude /// Additional width of back view, when it grows @IBInspectable open var additionalWidth: CGFloat = CGFloat.greatestFiniteMagnitude /// Should front view drow shadow to bottom or not @IBInspectable open var dropShadow: Bool = true // MARK: Constants struct Constants { static let backContainer = "backContainerViewKey" static let shadowView = "shadowViewKey" static let frontContainer = "frontContainerKey" static let backContainerY = "backContainerYKey" static let frontContainerY = "frontContainerYKey" } // MARK: Vars /// The view used as the face of the cell must connectid from xib or storyboard. @IBOutlet open var frontContainerView: UIView! /// The view used as the back of the cell must connectid from xib or storyboard. @IBOutlet open var backContainerView: UIView! /// constraints for backContainerView must connectid from xib or storyboard @IBOutlet open var backConstraintY: NSLayoutConstraint! /// constraints for frontContainerView must connectid from xib or storyboard @IBOutlet open var frontConstraintY: NSLayoutConstraint! var shadowView: UIView? /// A Boolean value that indicates whether the cell is opened. open var isOpened = false // MARK: inits /** Initializes a UICollectionViewCell from data in a given unarchiver. - parameter aDecoder: An unarchiver object. - returns: An initialized UICollectionViewCell object. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureOutletFromDecoder(aDecoder) } /** Initializes and returns a newly allocated view object with the specified frame rectangle. - parameter frame: The frame rectangle for the view - returns: An initialized UICollectionViewCell object. */ override init(frame: CGRect) { super.init(frame: frame) commonInit() } } // MARK: life cicle extension BasePageCollectionCell { open override func awakeFromNib() { super.awakeFromNib() commonInit() } fileprivate func commonInit() { configurationViews() shadowView = createShadowViewOnView(frontContainerView) } } // MARK: Control extension BasePageCollectionCell { /** Open or close cell. - parameter isOpen: Contains the value true if the cell should display open state, if false should display close state. - parameter animated: Set to true if the change in selection state is animated. */ public func cellIsOpen(_ isOpen: Bool, animated: Bool = true) { if isOpen == isOpened { return } if ySpacing == .greatestFiniteMagnitude { frontConstraintY.constant = isOpen == true ? -frontContainerView.bounds.size.height / 6 : 0 backConstraintY.constant = isOpen == true ? frontContainerView.bounds.size.height / 6 - yOffset / 2 : 0 } else { frontConstraintY.constant = isOpen == true ? -ySpacing / 2 : 0 backConstraintY.constant = isOpen == true ? ySpacing / 2 : 0 } if let widthConstant = backContainerView.getConstraint(.width) { if additionalWidth == .greatestFiniteMagnitude { widthConstant.constant = isOpen == true ? frontContainerView.bounds.size.width + yOffset : frontContainerView.bounds.size.width } else { widthConstant.constant = isOpen == true ? frontContainerView.bounds.size.width + additionalWidth : frontContainerView.bounds.size.width } } if let heightConstant = backContainerView.getConstraint(.height) { if additionalHeight == .greatestFiniteMagnitude { heightConstant.constant = isOpen == true ? frontContainerView.bounds.size.height + yOffset : frontContainerView.bounds.size.height } else { heightConstant.constant = isOpen == true ? frontContainerView.bounds.size.height + additionalHeight : frontContainerView.bounds.size.height } } isOpened = isOpen if animated == true { UIView.animate(withDuration: 0.3, delay: 0, options: UIView.AnimationOptions(), animations: { self.contentView.layoutIfNeeded() }, completion: nil) } else { contentView.layoutIfNeeded() } } } // MARK: Configuration extension BasePageCollectionCell { fileprivate func configurationViews() { backContainerView.layer.masksToBounds = true backContainerView.layer.cornerRadius = 5 frontContainerView.layer.masksToBounds = true frontContainerView.layer.cornerRadius = 5 contentView.layer.masksToBounds = false layer.masksToBounds = false } fileprivate func createShadowViewOnView(_ view: UIView?) -> UIView? { guard let view = view else { return nil } let shadow = Init(UIView(frame: .zero)) { $0.backgroundColor = UIColor(white: 0, alpha: 0) $0.translatesAutoresizingMaskIntoConstraints = false $0.layer.masksToBounds = false if dropShadow { $0.layer.shadowColor = UIColor.black.cgColor $0.layer.shadowRadius = 10 $0.layer.shadowOpacity = 0.3 $0.layer.shadowOffset = CGSize(width: 0, height: 0) } } contentView.insertSubview(shadow, belowSubview: view) // create constraints let sizeConstaints: [(NSLayoutConstraint.Attribute, CGFloat)] = [(NSLayoutConstraint.Attribute.width, 0.8), (NSLayoutConstraint.Attribute.height, 0.9)] for info: (attribute: NSLayoutConstraint.Attribute, scale: CGFloat) in sizeConstaints { if let frontViewConstraint = view.getConstraint(info.attribute) { shadow >>>- { $0.attribute = info.attribute $0.constant = frontViewConstraint.constant * info.scale return } } } let centerConstraints: [(NSLayoutConstraint.Attribute, CGFloat)] = [(NSLayoutConstraint.Attribute.centerX, 0), (NSLayoutConstraint.Attribute.centerY, 30)] for info: (attribute: NSLayoutConstraint.Attribute, offset: CGFloat) in centerConstraints { (contentView, shadow, view) >>>- { $0.attribute = info.attribute $0.constant = info.offset return } } // size shadow let width = shadow.getConstraint(.width)?.constant let height = shadow.getConstraint(.height)?.constant shadow.layer.shadowPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width!, height: height!), cornerRadius: 0).cgPath return shadow } func configureCellViewConstraintsWithSize(_ size: CGSize) { guard isOpened == false && frontContainerView.getConstraint(.width)?.constant != size.width else { return } [frontContainerView, backContainerView].forEach { let constraintWidth = $0?.getConstraint(.width) constraintWidth?.constant = size.width let constraintHeight = $0?.getConstraint(.height) constraintHeight?.constant = size.height } } } // MARK: NSCoding extension BasePageCollectionCell { fileprivate func highlightedImageFalseOnView(_ view: UIView) { for item in view.subviews { if case let imageView as UIImageView = item { imageView.isHighlighted = false } if item.subviews.count > 0 { highlightedImageFalseOnView(item) } } } fileprivate func copyShadowFromView(_ fromView: UIView, toView: UIView) { fromView.layer.shadowPath = toView.layer.shadowPath fromView.layer.masksToBounds = toView.layer.masksToBounds fromView.layer.shadowColor = toView.layer.shadowColor fromView.layer.shadowRadius = toView.layer.shadowRadius fromView.layer.shadowOpacity = toView.layer.shadowOpacity fromView.layer.shadowOffset = toView.layer.shadowOffset } func copyCell() -> BasePageCollectionCell? { highlightedImageFalseOnView(contentView) let data = NSKeyedArchiver.archivedData(withRootObject: self) guard case let copyView as BasePageCollectionCell = NSKeyedUnarchiver.unarchiveObject(with: data), let shadowView = self.shadowView else { return nil } // configure copyView.backContainerView.layer.masksToBounds = backContainerView.layer.masksToBounds copyView.backContainerView.layer.cornerRadius = backContainerView.layer.cornerRadius copyView.frontContainerView.layer.masksToBounds = frontContainerView.layer.masksToBounds copyView.frontContainerView.layer.cornerRadius = frontContainerView.layer.cornerRadius // copy shadow layer copyShadowFromView(copyView.shadowView!, toView: shadowView) for index in 0 ..< copyView.frontContainerView.subviews.count { copyShadowFromView(copyView.frontContainerView.subviews[index], toView: frontContainerView.subviews[index]) } return copyView } open override func encode(with coder: NSCoder) { super.encode(with: coder) coder.encode(backContainerView, forKey: Constants.backContainer) coder.encode(frontContainerView, forKey: Constants.frontContainer) coder.encode(frontConstraintY, forKey: Constants.frontContainerY) coder.encode(backConstraintY, forKey: Constants.backContainerY) coder.encode(shadowView, forKey: Constants.shadowView) } fileprivate func configureOutletFromDecoder(_ coder: NSCoder) { if case let shadowView as UIView = coder.decodeObject(forKey: Constants.shadowView) { self.shadowView = shadowView } if case let backView as UIView = coder.decodeObject(forKey: Constants.backContainer) { backContainerView = backView } if case let frontView as UIView = coder.decodeObject(forKey: Constants.frontContainer) { frontContainerView = frontView } if case let constraint as NSLayoutConstraint = coder.decodeObject(forKey: Constants.frontContainerY) { frontConstraintY = constraint } if case let constraint as NSLayoutConstraint = coder.decodeObject(forKey: Constants.backContainerY) { backConstraintY = constraint } } }
mit
06ae4fcc434cf4120c7030fe504a0ad5
36.426667
162
0.666014
5.133973
false
false
false
false
rchatham/PeerConnectivity
Sources/PeerAdvertiserAssisstantEventProducer.swift
1
1152
// // PeerAdvertiserAssisstant.swift // PeerConnectivity // // Created by Reid Chatham on 12/23/15. // Copyright © 2015 Reid Chatham. All rights reserved. // import Foundation import MultipeerConnectivity internal enum PeerAdvertiserAssisstantEvent { case none case didDissmissInvitation case willPresentInvitation } internal class PeerAdvertiserAssisstantEventProducer: NSObject { fileprivate let observer : Observable<PeerAdvertiserAssisstantEvent> internal init(observer: Observable<PeerAdvertiserAssisstantEvent>) { self.observer = observer } } extension PeerAdvertiserAssisstantEventProducer: MCAdvertiserAssistantDelegate { internal func advertiserAssistantDidDismissInvitation(_ advertiserAssistant: MCAdvertiserAssistant) { let event: PeerAdvertiserAssisstantEvent = .didDissmissInvitation self.observer.value = event } internal func advertiserAssistantWillPresentInvitation(_ advertiserAssistant: MCAdvertiserAssistant) { let event: PeerAdvertiserAssisstantEvent = .willPresentInvitation self.observer.value = event } }
mit
45c3fa97caffd089cec681bb07f993a7
27.775
106
0.757602
4.85654
false
false
false
false
xedin/swift
test/decl/class/circular_inheritance.swift
3
2639
// RUN: rm -rf %t/stats-dir // RUN: mkdir -p %t/stats-dir // RUN: %target-typecheck-verify-swift // RUN: not %target-swift-frontend -typecheck -debug-cycles %s -output-request-graphviz %t.dot -stats-output-dir %t/stats-dir 2> %t.cycles // RUN: %FileCheck %s < %t.cycles // RUN: %FileCheck -check-prefix CHECK-DOT %s < %t.dot // Check that we produced superclass type requests. // RUN: %{python} %utils/process-stats-dir.py --evaluate 'SuperclassTypeRequest == 17' %t/stats-dir class Left // expected-error {{circular reference}} : Right.Hand { // expected-note {{through reference here}} class Hand {} } class Right // expected-note {{through reference here}} : Left.Hand { // expected-note {{through reference here}} class Hand {} } class C : B { } // expected-error{{'C' inherits from itself}} class B : A { } // expected-note{{class 'B' declared here}} class A : C { } // expected-note{{class 'A' declared here}} class TrivialCycle : TrivialCycle {} // expected-error{{'TrivialCycle' inherits from itself}} protocol P : P {} // expected-error {{protocol 'P' refines itself}} class Isomorphism : Automorphism { } class Automorphism : Automorphism { } // expected-error{{'Automorphism' inherits from itself}} // FIXME: Useless error let _ = A() // expected-error{{'A' cannot be constructed because it has no accessible initializers}} class Outer { class Inner : Outer {} } class Outer2 // expected-error {{circular reference}} : Outer2.Inner { // expected-note {{through reference here}} class Inner {} } class Outer3 // expected-error {{circular reference}} : Outer3.Inner<Int> { // expected-note {{through reference here}} class Inner<T> {} } // CHECK: ===CYCLE DETECTED=== // CHECK-NEXT: `--{{.*}}SuperclassDeclRequest({{.*Left}} // CHECK: `--{{.*}}InheritedDeclsReferencedRequest(circular_inheritance.(file).Left@ // CHECK: `--{{.*}}SuperclassDeclRequest // CHECK: `--{{.*}}InheritedDeclsReferencedRequest(circular_inheritance.(file).Right@ // CHECK: `--{{.*}}SuperclassDeclRequest{{.*(cyclic dependency)}} // CHECK-DOT: digraph Dependencies // CHECK-DOT: label="InheritedTypeRequest protocol Initable { init() // expected-note@-1 {{protocol requires initializer 'init()' with type '()'; do you want to add a stub?}} } protocol Shape : Circle {} class Circle : Initable & Circle {} // expected-error@-1 {{'Circle' inherits from itself}} // expected-error@-2 {{type 'Circle' does not conform to protocol 'Initable'}} func crash() { Circle() // expected-error@-1 {{'Circle' cannot be constructed because it has no accessible initializers}} }
apache-2.0
2fa12ac40d770ec27d3b2c663fdcf929
35.150685
138
0.672982
3.706461
false
false
false
false
groue/GRMustache.swift
Sources/SwiftStandardLibrary.swift
2
14869
// The MIT License // // Copyright (c) 2016 Gwendal Roué // // 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. /// GRMustache provides built-in support for rendering `Double`. extension Double : MustacheBoxable { /// `Double` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{double}}` is rendered with built-in Swift String Interpolation. /// Custom formatting can be explicitly required with NumberFormatter, as in /// `{{format(a)}}` (see `Formatter`). /// /// - `{{#double}}...{{/double}}` renders if and only if `double` is not 0 (zero). /// /// - `{{^double}}...{{/double}}` renders if and only if `double` is 0 (zero). public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: (self != 0.0), render: { (info: RenderingInfo) in switch info.tag.type { case .variable: // {{ double }} return Rendering("\(self)") case .section: if info.enumerationItem { // {{# doubles }}...{{/ doubles }} return try info.tag.render(info.context.extendedContext(Box(self))) } else { // {{# double }}...{{/ double }} // // Doubles do not enter the context stack when used in a // boolean section. // // This behavior must not change: // https://github.com/groue/GRMustache/issues/83 return try info.tag.render(info.context) } } }) } } /// GRMustache provides built-in support for rendering `Float`. extension Float : MustacheBoxable { /// `Float` adopts the `MustacheBoxable` protocol so that it can feed Mustache /// templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{float}}` is rendered with built-in Swift String Interpolation. /// Custom formatting can be explicitly required with NumberFormatter, as in /// `{{format(a)}}` (see `Formatter`). /// /// - `{{#float}}...{{/float}}` renders if and only if `float` is not 0 (zero). /// /// - `{{^float}}...{{/float}}` renders if and only if `float` is 0 (zero). public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: (self != 0.0), render: { (info: RenderingInfo) in switch info.tag.type { case .variable: // {{ float }} return Rendering("\(self)") case .section: if info.enumerationItem { // {{# floats }}...{{/ floats }} return try info.tag.render(info.context.extendedContext(Box(self))) } else { // {{# float }}...{{/ float }} // // Floats do not enter the context stack when used in a // boolean section. // // This behavior must not change: // https://github.com/groue/GRMustache/issues/83 return try info.tag.render(info.context) } } }) } } /// GRMustache provides built-in support for rendering `String`. extension String : MustacheBoxable { /// `String` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{string}}` renders the string, HTML-escaped. /// /// - `{{{string}}}` renders the string, *not* HTML-escaped. /// /// - `{{#string}}...{{/string}}` renders if and only if `string` is not empty. /// /// - `{{^string}}...{{/string}}` renders if and only if `string` is empty. /// /// HTML-escaping of `{{string}}` tags is disabled for Text templates: see /// `Configuration.contentType` for a full discussion of the content type of /// templates. /// /// /// ### Keys exposed to templates /// /// A string can be queried for the following keys: /// /// - `length`: the number of characters in the string. public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: (self.count > 0), keyedSubscript: { (key: String) in switch key { case "length": return self.count default: return nil } }) } } /// GRMustache provides built-in support for rendering `Bool`. extension Bool : MustacheBoxable { /// `Bool` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{bool}}` renders as `0` or `1`. /// /// - `{{#bool}}...{{/bool}}` renders if and only if `bool` is true. /// /// - `{{^bool}}...{{/bool}}` renders if and only if `bool` is false. public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: self, render: { (info: RenderingInfo) in switch info.tag.type { case .variable: // {{ bool }} return Rendering("\(self ? 1 : 0)") // Behave like [NSNumber numberWithBool:] case .section: if info.enumerationItem { // {{# bools }}...{{/ bools }} return try info.tag.render(info.context.extendedContext(Box(self))) } else { // {{# bool }}...{{/ bool }} // // Bools do not enter the context stack when used in a // boolean section. // // This behavior must not change: // https://github.com/groue/GRMustache/issues/83 return try info.tag.render(info.context) } } }) } } /// GRMustache provides built-in support for rendering `Int64`. extension Int64 : MustacheBoxable { /// `Int64` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{int}}` is rendered with built-in Swift String Interpolation. /// Custom formatting can be explicitly required with NumberFormatter, /// as in `{{format(a)}}` (see `Formatter`). /// /// - `{{#int}}...{{/int}}` renders if and only if `int` is not 0 (zero). /// /// - `{{^int}}...{{/int}}` renders if and only if `int` is 0 (zero). public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: (self != 0), render: { (info: RenderingInfo) in switch info.tag.type { case .variable: // {{ int }} return Rendering("\(self)") case .section: if info.enumerationItem { // {{# ints }}...{{/ ints }} return try info.tag.render(info.context.extendedContext(Box(self))) } else { // {{# int }}...{{/ int }} // // Ints do not enter the context stack when used in a // boolean section. // // This behavior must not change: // https://github.com/groue/GRMustache/issues/83 return try info.tag.render(info.context) } } }) } } /// GRMustache provides built-in support for rendering `Int`. extension Int : MustacheBoxable { /// `Int` adopts the `MustacheBoxable` protocol so that it can feed Mustache /// templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{int}}` is rendered with built-in Swift String Interpolation. /// Custom formatting can be explicitly required with NumberFormatter, as /// in `{{format(a)}}` (see `Formatter`). /// /// - `{{#int}}...{{/int}}` renders if and only if `int` is not 0 (zero). /// /// - `{{^int}}...{{/int}}` renders if and only if `int` is 0 (zero). public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: (self != 0), render: { (info: RenderingInfo) in switch info.tag.type { case .variable: // {{ int }} return Rendering("\(self)") case .section: if info.enumerationItem { // {{# ints }}...{{/ ints }} return try info.tag.render(info.context.extendedContext(Box(self))) } else { // {{# int }}...{{/ int }} // // Ints do not enter the context stack when used in a // boolean section. // // This behavior must not change: // https://github.com/groue/GRMustache/issues/83 return try info.tag.render(info.context) } } }) } } /// GRMustache provides built-in support for rendering `UInt64`. extension UInt64 : MustacheBoxable { /// `UInt64` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{uint}}` is rendered with built-in Swift String Interpolation. /// Custom formatting can be explicitly required with NumberFormatter, as /// in `{{format(a)}}` (see `Formatter`). /// /// - `{{#uint}}...{{/uint}}` renders if and only if `uint` is not 0 (zero). /// /// - `{{^uint}}...{{/uint}}` renders if and only if `uint` is 0 (zero). public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: (self != 0), render: { (info: RenderingInfo) in switch info.tag.type { case .variable: // {{ uint }} return Rendering("\(self)") case .section: if info.enumerationItem { // {{# uints }}...{{/ uints }} return try info.tag.render(info.context.extendedContext(Box(self))) } else { // {{# uint }}...{{/ uint }} // // Uints do not enter the context stack when used in a // boolean section. // // This behavior must not change: // https://github.com/groue/GRMustache/issues/83 return try info.tag.render(info.context) } } }) } } /// GRMustache provides built-in support for rendering `UInt`. extension UInt : MustacheBoxable { /// `UInt` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{uint}}` is rendered with built-in Swift String Interpolation. /// Custom formatting can be explicitly required with NumberFormatter, as /// in `{{format(a)}}` (see `Formatter`). /// /// - `{{#uint}}...{{/uint}}` renders if and only if `uint` is not 0 (zero). /// /// - `{{^uint}}...{{/uint}}` renders if and only if `uint` is 0 (zero). public var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: (self != 0), render: { (info: RenderingInfo) in switch info.tag.type { case .variable: // {{ uint }} return Rendering("\(self)") case .section: if info.enumerationItem { // {{# uints }}...{{/ uints }} return try info.tag.render(info.context.extendedContext(Box(self))) } else { // {{# uint }}...{{/ uint }} // // Uints do not enter the context stack when used in a // boolean section. // // This behavior must not change: // https://github.com/groue/GRMustache/issues/83 return try info.tag.render(info.context) } } }) } }
mit
eb71422fab569e3453c39a34c693183a
36.832061
97
0.486616
5.151767
false
false
false
false
Piwigo/Piwigo-Mobile
piwigoKit/Network/pwg.categories/pwg.categories.move.swift
1
2155
// // pwg.categories.move.swift // piwigoKit // // Created by Eddy Lelièvre-Berna on 02/06/2022. // Copyright © 2022 Piwigo.org. All rights reserved. // import Foundation // MARK: - pwg.categories.setRepresentative public let kPiwigoCategoriesMove = "format=json&method=pwg.categories.move" public struct CategoriesMoveJSON: Decodable { public var status: String? public var success = false public var errorCode = 0 public var errorMessage = "" private enum RootCodingKeys: String, CodingKey { case status = "stat" case errorCode = "err" case errorMessage = "message" } private enum ErrorCodingKeys: String, CodingKey { case code = "code" case message = "msg" } public init(from decoder: Decoder) throws { // Root container keyed by RootCodingKeys let rootContainer = try decoder.container(keyedBy: RootCodingKeys.self) // Status returned by Piwigo status = try rootContainer.decodeIfPresent(String.self, forKey: .status) if status == "ok" { success = true } else if status == "fail" { do { // Retrieve Piwigo server error errorCode = try rootContainer.decode(Int.self, forKey: .errorCode) errorMessage = try rootContainer.decode(String.self, forKey: .errorMessage) } catch { // Error container keyed by ErrorCodingKeys ("format=json" forgotten in call) let errorContainer = try rootContainer.nestedContainer(keyedBy: ErrorCodingKeys.self, forKey: .errorCode) errorCode = Int(try errorContainer.decode(String.self, forKey: .code)) ?? NSNotFound errorMessage = try errorContainer.decode(String.self, forKey: .message) } } else { // Unexpected Piwigo server error errorCode = -1 errorMessage = NSLocalizedString("serverUnknownError_message", comment: "Unexpected error encountered while calling server method with provided parameters.") } } }
mit
1b4667057e45480da3a3e43b0e38ad9c
33.174603
169
0.622387
4.882086
false
false
false
false
mitchellporter/ios-animations
Animation/MainViewController.swift
2
4324
import UIKit /* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. This licensed material is licensed under the Apache 2.0 license. http://www.apache.org/licenses/LICENSE-2.0. */ /** Main menu of the sampler, providing buttons to get to any of the sample scenarios. There is no code related to the motion samples in this view controller. */ class MainViewController: UIViewController, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate { // MARK: - Outlets @IBOutlet weak var noteViewLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var noteViewHeightConstraint: NSLayoutConstraint! // MARK: - Constants, Properties var noteViewHeight: CGFloat? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // only enable scrolling if there is enough content tableView.alwaysBounceVertical = false } // MARK: - Scroll View func scrollViewDidScroll(scrollView: UIScrollView) { let scrollOffset = scrollView.contentOffset.y let maxScrollOffset: CGFloat = 30 let alphaPercentage = (150 - (scrollOffset * 10)) / 150 * 2 if noteViewHeight == nil { noteViewHeight = noteViewHeightConstraint.constant } let offsetToShowNote: CGFloat = -20 let offsetToHideNote: CGFloat = 15 } // MARK: - Table View func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 4 default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCellID") as! TableViewCell cell.backgroundColor = UIColor.clearColor() // Display text switch (indexPath.section, indexPath.row) { case (0, 0): cell.label.text = "Tab Bar" case (0, 1): cell.label.text = "Search" case (0, 2): cell.label.text = "Modal" case (0, 3): cell.label.text = "Dropdown" default: cell.label.text = "" } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Row selected, view storyboard by ID switch (indexPath.section, indexPath.row) { case (0, 0): showView("TabBar", viewControllerID: "TabBarControllerID") case (0, 1): showView("Search", viewControllerID: "SearchNavigationControllerID") case (0, 2): showView("Modal", viewControllerID: "ModalNavigationControllerID") case (0, 3): showView("Dropdown", viewControllerID: "DropdownViewControllerID") default:break } tableView.deselectRowAtIndexPath(indexPath, animated: false) } // MARK: - Flow // The view controller is pushed in a different way depending if it's inside a // navigation controller. func showView(storyboard: String, viewControllerID: String) { let sb = UIStoryboard(name: storyboard, bundle: nil) let vc = sb.instantiateViewControllerWithIdentifier(viewControllerID) as! UIViewController if vc is UINavigationController { var nav = vc as! UINavigationController var view = nav.viewControllers.first as! UIViewController self.navigationController?.pushViewController(view, animated: true) } else { self.navigationController?.pushViewController(vc, animated: true) } } // MARK: - Appearance override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
apache-2.0
8c34e634233bd129d0b5863f2aa5df16
31.503759
110
0.618089
5.458333
false
false
false
false
IBM-Swift/Kitura
Sources/Kitura/staticFileServer/StaticFileServer.swift
1
8374
/* * Copyright IBM Corporation 2016,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. */ import Foundation import LoggerAPI // MARK: StaticFileServer /** A router middleware that serves static files from a given path. By default, it will serve files from the "/public" directory. ### Usage Example: ### The example below creates and registers a `StaticFileServer` on the "/example" route. When the router is running, A user can make a request that matches the "/example" path (e.g. localhost:8080/example/hello.html). The static file server would look inside its "/files" folder for a file with the same name as the path following "/example" (e.g. "hello.html"). If a file is found it is sent as a response to that request, otherwise the next handler is called. ```swift let router = Router() router.all("/example", middleware: StaticFileServer(path: "./files")) ``` */ open class StaticFileServer: RouterMiddleware { // MARK: Configuration Options /// Cache configuration options for StaticFileServer. public struct CacheOptions { let addLastModifiedHeader: Bool let maxAgeCacheControlHeader: Int let generateETag: Bool /// Initialize a CacheOptions instance. /// /// - Parameter addLastModifiedHeader: an indication whether to set /// "Last-Modified" header in the response. /// - Parameter maxAgeCacheControlHeader: a max-age in seconds for /// "max-age" value in "Cache-Control" header in the response /// - Parameter generateETag: an indication whether to set "Etag" /// header in the response. public init(addLastModifiedHeader: Bool = true, maxAgeCacheControlHeader: Int = 0, generateETag: Bool = true) { self.addLastModifiedHeader = addLastModifiedHeader self.maxAgeCacheControlHeader = maxAgeCacheControlHeader self.generateETag = generateETag } } /// Configuration options for StaticFileServer. public struct Options { let possibleExtensions: [String] let redirect: Bool let serveIndexForDirectory: Bool let cacheOptions: CacheOptions let acceptRanges: Bool let defaultIndex: String? /// Initialize an Options instance. /// /// - Parameter possibleExtensions: an array of file extensions to be added /// to the file name in case the file was not found. The extensions are /// added in the order they appear in the array, and a new search is /// performed. /// - Parameter serveIndexForDirectory: an indication whether to serve /// "index.html" file the requested path is a directory. /// - Parameter redirect: an indication whether to redirect to trailing /// "/" when the requested path is a directory. /// - Parameter cacheOptions: cache options for StaticFileServer. /// - Parameter defaultIndex: A default index, like "/index.html", to be served if the /// requested path is not found. This is intended to be used by single page applications /// that wish to fallback to a default index when a requested path is not found, and where /// that path is not a file request. It will be assumed that the default index is reachable /// from the root directory configured with the StaticFileServer. Here's a usage example: /// ```swift /// let router = Router() /// router.all("/", middleware: StaticFileServer(defaultIndex: "/index.html")) /// ``` public init(possibleExtensions: [String] = [], serveIndexForDirectory: Bool = true, redirect: Bool = true, cacheOptions: CacheOptions = CacheOptions(), acceptRanges: Bool = true, defaultIndex: String? = nil) { self.possibleExtensions = possibleExtensions self.serveIndexForDirectory = serveIndexForDirectory self.redirect = redirect self.cacheOptions = cacheOptions self.acceptRanges = acceptRanges self.defaultIndex = defaultIndex } } /// The absolute (fully qualified) root serving path for this `StaticFileServer`, /// for example: `/Users/Dave/MyKituraProj/./public` public let absoluteRootPath: String let fileServer: FileServer // MARK: Initializer /// Initializes a `StaticFileServer` instance. /// /// - Parameter path: a root directory for file serving. /// - Parameter options: configuration options for StaticFileServer. /// - Parameter customResponseHeadersSetter: an object of a class that /// implements `ResponseHeadersSetter` protocol providing a custom method to set /// the headers of the response. public init(path: String = "./public", options: Options = Options(), customResponseHeadersSetter: ResponseHeadersSetter? = nil) { let rootPathAbsolute = StaticFileServer.ResourcePathHandler.getAbsolutePath(for: path) absoluteRootPath = rootPathAbsolute // If the supplied path does not exist log a warning as the path could be created dynamically at runtime. // If the supplied path exists and is not a directory then log an error. var isDirectory = ObjCBool(false) let pathExists = FileManager.default.fileExists(atPath: absoluteRootPath, isDirectory: &isDirectory) #if !os(Linux) || swift(>=4.1) let isDirectoryBool = isDirectory.boolValue #else let isDirectoryBool = isDirectory #endif if !pathExists { Log.warning("StaticFileServer being initialised with invalid path: \(rootPathAbsolute)") } else if !isDirectoryBool { Log.error("StaticFileServer should not be initialised with a path that resolves to a file") } let cacheOptions = options.cacheOptions let cacheRelatedHeadersSetter = CacheRelatedHeadersSetter(addLastModifiedHeader: cacheOptions.addLastModifiedHeader, maxAgeCacheControlHeader: cacheOptions.maxAgeCacheControlHeader, generateETag: cacheOptions.generateETag) let responseHeadersSetter = CompositeRelatedHeadersSetter(setters: cacheRelatedHeadersSetter, customResponseHeadersSetter) fileServer = FileServer(servingFilesPath: absoluteRootPath, options: options, responseHeadersSetter: responseHeadersSetter) } // MARK: Serve file /// Handle the request - serve static file. /// /// - Parameter request: The `RouterRequest` object used to work with the incoming /// HTTP request. /// - Parameter response: The `RouterResponse` object used to respond to the /// HTTP request. /// - Parameter next: The closure called to invoke the next handler or middleware /// associated with the request. open func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { defer { next() } guard request.serverRequest.method == "GET" || request.serverRequest.method == "HEAD" else { return } guard let filePath = fileServer.getFilePath(from: request) else { return } guard let requestPath = request.parsedURL.path else { return } let queryString: String = { if let queryString = request.parsedURL.query { return "?\(queryString)" } return "" }() fileServer.serveFile(filePath, requestPath: requestPath, queryString: queryString, response: response) } }
apache-2.0
3e4cd27b7aed93058ebd1c7a25df4634
43.780749
146
0.652615
5.109213
false
false
false
false
iAugux/Weboot
Weboot/WBTimelineViewController.swift
1
7680
// // HomeViewController.swift // iAugus // // Created by Augus on 4/25/15. // Copyright (c) 2015 Augus. All rights reserved. // import UIKit class WBTimelineViewController: WBBaseViewController, WBNewWeiboViewControllerDelegate { var cellHeight: CGFloat? var statuses: NSMutableArray? var query: WeiboRequestOperation? var maxId: Int? var numberOfRows: Int? var timelineModel: WBTimelineModel! // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() self.numberOfRows = defaultNumberOfStatusesInTheFirstTime self.timelineModel = WBTimelineModel() self.showCurrentAccountNameOnTimeline() self.loadStatuses() self.setupLoadmore() // register weibo cell self.tableView?.registerNib(UINib(nibName: MainStoryboard.NibNames.TimelineTableViewCell, bundle: nil), forCellReuseIdentifier: MainStoryboard.CellIdentifiers.timelineTableViewCell) self.tableView?.tableFooterView = UIView(frame: CGRectZero) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !(Weibo.getWeibo().isAuthenticated()){ showLoginButton() } else { showLogoutButton() } self.tableView?.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - set navigationItem' title to name of currentAccount func showCurrentAccountNameOnTimeline(){ if Weibo.getWeibo().isAuthenticated(){ let nameOfCurrentAccount = Weibo.getWeibo().currentAccount().user.name self.navigationItem.title = nameOfCurrentAccount } } // MARK: - Post new weibo override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == kNewWeiboSegue { let detailVC = segue.destinationViewController as! UINavigationController let newWeiboVC = detailVC.viewControllers.first as! WBNewWeiboViewController newWeiboVC.delegate = self } } func loadDataAfterPostNewWeibo() { self.loadStatuses() } // MARK: - login or logout func showLoginButton(){ let loginButton = UIBarButtonItem(title: "Login", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(WBTimelineViewController.loginWeibo)) self.navigationItem.leftBarButtonItem = loginButton } func showLogoutButton(){ let logoutButton = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: #selector(WBTimelineViewController.logoutWeibo)) self.navigationItem.leftBarButtonItem = logoutButton self.dismissViewControllerAnimated(true, completion: nil) } func loginWeibo(){ if !(Weibo.getWeibo().isAuthenticated()){ print("not authenticated! and authenticating...") Weibo.getWeibo().authorizeWithCompleted({ account, error in if error == nil{ NSLog("sign in successfully \(account.user.screenName)") self.loadStatuses() self.showCurrentAccountNameOnTimeline() self.automaticPullingDownToRefresh() // self.tableView.reloadData() } else{ NSLog("failed to sign in \(error)") } }) } else{ print("has been already authenticated!") } } func logoutWeibo(){ let alertController = UIAlertController(title: "Log Out", message: "Are you sure to logout", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil) let confirmAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action in Weibo.getWeibo().signOut() self.tableView.dataSource = nil self.tableView.reloadData() }) alertController.addAction(confirmAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } func setupLoadmore(){ print("start to load more") self.tableView?.addFooterWithCallback({ if self.maxId < Int(kNumberOfTimelineRow) { self.loadMoreStatuses(Int32(numberOfLoadmoreStatuses)) } else { UIApplication.topMostViewController()?.view.makeToast(message: "F**k Sina! No more data allowed.", duration: 0.7, position: HRToastPositionCenter) } self.tableView?.footerEndRefreshing() }) } } // MARK: - load data extension WBTimelineViewController { override func loadStatuses(){ query = WeiboRequestOperation() statuses = nil if query != nil { query!.cancel() } query = Weibo.getWeibo().queryTimeline(StatusTimelineFriends, count: kNumberOfTimelineRow , completed: ({ statuses, error in if error != nil{ self.statuses = nil NSLog("error: \(error) , please login...") } else{ self.statuses = statuses self.maxId = defaultNumberOfStatusesInTheFirstTime } self.query = nil self.tableView?.reloadData() self.refreshControl!.endRefreshing() })) } func loadMoreStatuses(count: Int32){ query = WeiboRequestOperation() if query != nil { query?.cancel() } query = Weibo.getWeibo().queryTimeline(StatusTimelineFriends, sinceId: Int64(statuses!.count), count: count, completed: { (statuses , error ) -> Void in print("loading more") if error != nil{ self.statuses = nil NSLog("error: \(error) , please login...") } else{ self.statuses?.addObjectsFromArray(statuses as [AnyObject]) self.numberOfRows? += statuses.count self.maxId! += numberOfLoadmoreStatuses } self.query = nil self.tableView.reloadData() self.refreshControl!.endRefreshing() }) } } // MARK: - TableViewDataSource extension WBTimelineViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if query != nil { return 0 } if statuses == nil{ return 0 }else{ return numberOfRows! } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.CellIdentifiers.timelineTableViewCell, forIndexPath: indexPath) as? WBTimelineTableViewCell { if let status = statuses?.objectAtIndex(indexPath.row) as? Status { cell.loadDataToCell(status) tableView.rowHeight = cell.cellHeight } return cell } return UITableViewCell() } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 200.0 } }
mit
19ee5b3a3aa042d75c360d3231088c53
33.133333
189
0.601172
5.501433
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/NSUserDefaults+WMFExtensions.swift
1
18003
let WMFAppResignActiveDateKey = "WMFAppResignActiveDateKey" let WMFShouldRestoreNavigationStackOnResume = "WMFShouldRestoreNavigationStackOnResume" let WMFAppSiteKey = "Domain" let WMFSearchURLKey = "WMFSearchURLKey" let WMFMigrateHistoryListKey = "WMFMigrateHistoryListKey" let WMFMigrateToSharedContainerKey = "WMFMigrateToSharedContainerKey" let WMFMigrateSavedPageListKey = "WMFMigrateSavedPageListKey" let WMFMigrateBlackListKey = "WMFMigrateBlackListKey" let WMFMigrateToFixArticleCacheKey = "WMFMigrateToFixArticleCacheKey3" let WMFDidMigrateToGroupKey = "WMFDidMigrateToGroup" let WMFDidMigrateToCoreDataFeedKey = "WMFDidMigrateToCoreDataFeedKey" let WMFMostRecentInTheNewsNotificationDateKey = "WMFMostRecentInTheNewsNotificationDate" let WMFInTheNewsMostRecentDateNotificationCountKey = "WMFInTheNewsMostRecentDateNotificationCount" let WMFDidShowNewsNotificatonInFeedKey = "WMFDidShowNewsNotificatonInFeedKey" let WMFInTheNewsNotificationsEnabled = "WMFInTheNewsNotificationsEnabled" let WMFFeedRefreshDateKey = "WMFFeedRefreshDateKey" let WMFLocationAuthorizedKey = "WMFLocationAuthorizedKey" let WMFPlacesDidPromptForLocationAuthorization = "WMFPlacesDidPromptForLocationAuthorization" let WMFExploreDidPromptForLocationAuthorization = "WMFExploreDidPromptForLocationAuthorization" let WMFPlacesHasAppeared = "WMFPlacesHasAppeared" let WMFAppThemeName = "WMFAppThemeName" let WMFIsImageDimmingEnabled = "WMFIsImageDimmingEnabled" let WMFIsAutomaticTableOpeningEnabled = "WMFIsAutomaticTableOpeningEnabled" let WMFDidShowThemeCardInFeed = "WMFDidShowThemeCardInFeed" let WMFDidShowReadingListCardInFeed = "WMFDidShowReadingListCardInFeed" let WMFDidShowEnableReadingListSyncPanelKey = "WMFDidShowEnableReadingListSyncPanelKey" let WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey = "WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey" let WMFDidShowLimitHitForUnsortedArticlesPanel = "WMFDidShowLimitHitForUnsortedArticlesPanel" let WMFDidShowSyncDisabledPanel = "WMFDidShowSyncDisabledPanel" let WMFDidShowSyncEnabledPanel = "WMFDidShowSyncEnabledPanel" let WMFDidSplitExistingReadingLists = "WMFDidSplitExistingReadingLists" let WMFDidShowTitleDescriptionEditingIntro = "WMFDidShowTitleDescriptionEditingIntro" let WMFDidShowFirstEditPublishedPanelKey = "WMFDidShowFirstEditPublishedPanelKey" let WMFIsSyntaxHighlightingEnabled = "WMFIsSyntaxHighlightingEnabled" let WMFSearchLanguageKey = "WMFSearchLanguageKey" @objc public enum WMFAppDefaultTabType: Int { case explore case settings } @objc public extension UserDefaults { @objc(WMFUserDefaultsKey) class Key: NSObject { @objc static let defaultTabType = "WMFDefaultTabTypeKey" static let isUserUnawareOfLogout = "WMFIsUserUnawareOfLogout" static let didShowDescriptionPublishedPanel = "WMFDidShowDescriptionPublishedPanel" static let didShowEditingOnboarding = "WMFDidShowEditingOnboarding" static let autoSignTalkPageDiscussions = "WMFAutoSignTalkPageDiscussions" } @objc static let wmf: UserDefaults = { #if WMF_NO_APP_GROUP return UserDefaults.standard #else guard let defaults = UserDefaults(suiteName: WMFApplicationGroupIdentifier) else { assertionFailure("Defaults not found!") return UserDefaults.standard } return defaults #endif }() @objc class func wmf_migrateToWMFGroupUserDefaultsIfNecessary() { let newDefaults = self.wmf let didMigrate = newDefaults.bool(forKey: WMFDidMigrateToGroupKey) if (!didMigrate) { let oldDefaults = UserDefaults.standard let oldDefaultsDictionary = oldDefaults.dictionaryRepresentation() for (key, value) in oldDefaultsDictionary { let lowercaseKey = key.lowercased() if lowercaseKey.hasPrefix("apple") || lowercaseKey.hasPrefix("ns") { continue } newDefaults.set(value, forKey: key) } newDefaults.set(true, forKey: WMFDidMigrateToGroupKey) } } @objc func wmf_dateForKey(_ key: String) -> Date? { return self.object(forKey: key) as? Date } @objc func wmf_appResignActiveDate() -> Date? { return self.wmf_dateForKey(WMFAppResignActiveDateKey) } @objc func wmf_setAppResignActiveDate(_ date: Date?) { if let date = date { self.set(date, forKey: WMFAppResignActiveDateKey) }else{ self.removeObject(forKey: WMFAppResignActiveDateKey) } } @objc var shouldRestoreNavigationStackOnResume: Bool { get { return bool(forKey: WMFShouldRestoreNavigationStackOnResume) } set { set(newValue, forKey: WMFShouldRestoreNavigationStackOnResume) } } @objc var wmf_lastAppVersion: String? { get { return string(forKey: "WMFLastAppVersion") } set { set(newValue, forKey: "WMFLastAppVersion") } } @objc func wmf_setFeedRefreshDate(_ date: Date) { self.set(date, forKey: WMFFeedRefreshDateKey) } @objc func wmf_feedRefreshDate() -> Date? { return self.wmf_dateForKey(WMFFeedRefreshDateKey) } @objc func wmf_setLocationAuthorized(_ authorized: Bool) { self.set(authorized, forKey: WMFLocationAuthorizedKey) } @objc var wmf_appTheme: Theme { return Theme.withName(string(forKey: WMFAppThemeName)) ?? Theme.standard } @objc func wmf_setAppTheme(_ theme: Theme) { set(theme.name, forKey: WMFAppThemeName) } @objc var wmf_isImageDimmingEnabled: Bool { get { return bool(forKey: WMFIsImageDimmingEnabled) } set { set(newValue, forKey: WMFIsImageDimmingEnabled) } } @objc var wmf_IsSyntaxHighlightingEnabled: Bool { get { if object(forKey: WMFIsSyntaxHighlightingEnabled) == nil { return true //default to highlighting enabled } return bool(forKey: WMFIsSyntaxHighlightingEnabled) } set { set(newValue, forKey: WMFIsSyntaxHighlightingEnabled) } } @objc var wmf_isAutomaticTableOpeningEnabled: Bool { get { return bool(forKey: WMFIsAutomaticTableOpeningEnabled) } set { set(newValue, forKey: WMFIsAutomaticTableOpeningEnabled) } } @objc var wmf_didShowThemeCardInFeed: Bool { get { return bool(forKey: WMFDidShowThemeCardInFeed) } set { set(newValue, forKey: WMFDidShowThemeCardInFeed) } } @objc var wmf_didShowReadingListCardInFeed: Bool { get { return bool(forKey: WMFDidShowReadingListCardInFeed) } set { set(newValue, forKey: WMFDidShowReadingListCardInFeed) } } @objc func wmf_locationAuthorized() -> Bool { return self.bool(forKey: WMFLocationAuthorizedKey) } @objc func wmf_setPlacesHasAppeared(_ hasAppeared: Bool) { self.set(hasAppeared, forKey: WMFPlacesHasAppeared) } @objc func wmf_placesHasAppeared() -> Bool { return self.bool(forKey: WMFPlacesHasAppeared) } @objc func wmf_setPlacesDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFPlacesDidPromptForLocationAuthorization) } @objc func wmf_placesDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFPlacesDidPromptForLocationAuthorization) } @objc func wmf_setExploreDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFExploreDidPromptForLocationAuthorization) } @objc func wmf_exploreDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFExploreDidPromptForLocationAuthorization) } @objc func wmf_setShowSearchLanguageBar(_ enabled: Bool) { self.set(NSNumber(value: enabled as Bool), forKey: "ShowLanguageBar") } @objc func wmf_showSearchLanguageBar() -> Bool { if let enabled = self.object(forKey: "ShowLanguageBar") as? NSNumber { return enabled.boolValue }else{ return false } } @objc var wmf_openAppOnSearchTab: Bool { get { return bool(forKey: "WMFOpenAppOnSearchTab") } set { set(newValue, forKey: "WMFOpenAppOnSearchTab") } } @objc func wmf_currentSearchLanguageDomain() -> URL? { if let url = self.url(forKey: WMFSearchURLKey) { return url }else if let language = self.object(forKey: WMFSearchLanguageKey) as? String { let url = NSURL.wmf_URL(withDefaultSiteAndlanguage: language) self.wmf_setCurrentSearchLanguageDomain(url) return url }else{ return nil } } @objc func wmf_setCurrentSearchLanguageDomain(_ url: URL?) { guard let url = url else{ self.removeObject(forKey: WMFSearchURLKey) return } guard !url.wmf_isNonStandardURL else{ return; } self.set(url, forKey: WMFSearchURLKey) } @objc func wmf_setDidShowWIconPopover(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowWIconPopover") } @objc func wmf_didShowWIconPopover() -> Bool { if let enabled = self.object(forKey: "ShowWIconPopover") as? NSNumber { return enabled.boolValue }else{ return false } } @objc func wmf_setDidShowMoreLanguagesTooltip(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowMoreLanguagesTooltip") } @objc func wmf_didShowMoreLanguagesTooltip() -> Bool { if let enabled = self.object(forKey: "ShowMoreLanguagesTooltip") as? NSNumber { return enabled.boolValue }else{ return false } } @objc func wmf_setTableOfContentsIsVisibleInline(_ visibleInline: Bool) { self.set(NSNumber(value: visibleInline as Bool), forKey: "TableOfContentsIsVisibleInline") } @objc func wmf_isTableOfContentsVisibleInline() -> Bool { if let enabled = self.object(forKey: "TableOfContentsIsVisibleInline") as? NSNumber { return enabled.boolValue }else{ return true } } @objc func wmf_setDidFinishLegacySavedArticleImageMigration(_ didFinish: Bool) { self.set(didFinish, forKey: "DidFinishLegacySavedArticleImageMigration2") } @objc func wmf_didFinishLegacySavedArticleImageMigration() -> Bool { return self.bool(forKey: "DidFinishLegacySavedArticleImageMigration2") } @objc func wmf_setDidMigrateHistoryList(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateHistoryListKey) } @objc func wmf_didMigrateHistoryList() -> Bool { return self.bool(forKey: WMFMigrateHistoryListKey) } @objc func wmf_setDidMigrateSavedPageList(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateSavedPageListKey) } @objc func wmf_didMigrateSavedPageList() -> Bool { return self.bool(forKey: WMFMigrateSavedPageListKey) } @objc func wmf_setDidMigrateBlackList(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateBlackListKey) } @objc func wmf_didMigrateBlackList() -> Bool { return self.bool(forKey: WMFMigrateBlackListKey) } @objc func wmf_setDidMigrateToFixArticleCache(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateToFixArticleCacheKey) } @objc func wmf_didMigrateToFixArticleCache() -> Bool { return self.bool(forKey: WMFMigrateToFixArticleCacheKey) } @objc func wmf_setDidMigrateToSharedContainer(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateToSharedContainerKey) } @objc func wmf_didMigrateToSharedContainer() -> Bool { return self.bool(forKey: WMFMigrateToSharedContainerKey) } @objc func wmf_setDidMigrateToNewFeed(_ didMigrate: Bool) { self.set(didMigrate, forKey: WMFDidMigrateToCoreDataFeedKey) } @objc func wmf_didMigrateToNewFeed() -> Bool { return self.bool(forKey: WMFDidMigrateToCoreDataFeedKey) } @objc func wmf_mostRecentInTheNewsNotificationDate() -> Date? { return self.wmf_dateForKey(WMFMostRecentInTheNewsNotificationDateKey) } @objc func wmf_setMostRecentInTheNewsNotificationDate(_ date: Date) { self.set(date, forKey: WMFMostRecentInTheNewsNotificationDateKey) } @objc func wmf_inTheNewsMostRecentDateNotificationCount() -> Int { return self.integer(forKey: WMFInTheNewsMostRecentDateNotificationCountKey) } @objc func wmf_setInTheNewsMostRecentDateNotificationCount(_ count: Int) { self.set(count, forKey: WMFInTheNewsMostRecentDateNotificationCountKey) } @objc func wmf_inTheNewsNotificationsEnabled() -> Bool { return self.bool(forKey: WMFInTheNewsNotificationsEnabled) } @objc func wmf_setInTheNewsNotificationsEnabled(_ enabled: Bool) { self.set(enabled, forKey: WMFInTheNewsNotificationsEnabled) } @objc func wmf_setDidShowNewsNotificationCardInFeed(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowNewsNotificatonInFeedKey) } @objc func wmf_didShowNewsNotificationCardInFeed() -> Bool { return self.bool(forKey: WMFDidShowNewsNotificatonInFeedKey) } @objc func wmf_setDidShowEnableReadingListSyncPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowEnableReadingListSyncPanelKey) } @objc func wmf_didShowEnableReadingListSyncPanel() -> Bool { return self.bool(forKey: WMFDidShowEnableReadingListSyncPanelKey) } @objc func wmf_setDidShowLoginToSyncSavedArticlesToReadingListPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) } @objc func wmf_didShowLoginToSyncSavedArticlesToReadingListPanel() -> Bool { return self.bool(forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) } @objc func wmf_setDidShowFirstEditPublishedPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowFirstEditPublishedPanelKey) } @objc func wmf_didShowFirstEditPublishedPanel() -> Bool { return self.bool(forKey: WMFDidShowFirstEditPublishedPanelKey) } @objc func wmf_didShowLimitHitForUnsortedArticlesPanel() -> Bool { return self.bool(forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) } @objc func wmf_setDidShowLimitHitForUnsortedArticlesPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) } @objc func wmf_didShowSyncDisabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncDisabledPanel) } @objc func wmf_setDidShowSyncDisabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncDisabledPanel) } @objc func wmf_didShowSyncEnabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncEnabledPanel) } @objc func wmf_setDidShowSyncEnabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncEnabledPanel) } @objc func wmf_didSplitExistingReadingLists() -> Bool { return self.bool(forKey: WMFDidSplitExistingReadingLists) } @objc func wmf_setDidSplitExistingReadingLists(_ didSplit: Bool) { self.set(didSplit, forKey: WMFDidSplitExistingReadingLists) } @objc var defaultTabType: WMFAppDefaultTabType { get { guard let defaultTabType = WMFAppDefaultTabType(rawValue: integer(forKey: UserDefaults.Key.defaultTabType)) else { let explore = WMFAppDefaultTabType.explore set(explore.rawValue, forKey: UserDefaults.Key.defaultTabType) return explore } return defaultTabType } set { set(newValue.rawValue, forKey: UserDefaults.Key.defaultTabType) wmf_openAppOnSearchTab = newValue == .settings } } @objc func wmf_didShowTitleDescriptionEditingIntro() -> Bool { return self.bool(forKey: WMFDidShowTitleDescriptionEditingIntro) } @objc func wmf_setDidShowTitleDescriptionEditingIntro(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowTitleDescriptionEditingIntro) } var isUserUnawareOfLogout: Bool { get { return bool(forKey: UserDefaults.Key.isUserUnawareOfLogout) } set { set(newValue, forKey: UserDefaults.Key.isUserUnawareOfLogout) } } var didShowDescriptionPublishedPanel: Bool { get { return bool(forKey: UserDefaults.Key.didShowDescriptionPublishedPanel) } set { set(newValue, forKey: UserDefaults.Key.didShowDescriptionPublishedPanel) } } @objc var didShowEditingOnboarding: Bool { get { return bool(forKey: UserDefaults.Key.didShowEditingOnboarding) } set { set(newValue, forKey: UserDefaults.Key.didShowEditingOnboarding) } } var autoSignTalkPageDiscussions: Bool { get { return bool(forKey: UserDefaults.Key.autoSignTalkPageDiscussions) } set { set(newValue, forKey: UserDefaults.Key.autoSignTalkPageDiscussions) } } #if UI_TEST @objc func wmf_isFastlaneSnapshotInProgress() -> Bool { return bool(forKey: "FASTLANE_SNAPSHOT") } #endif }
mit
bbe502f3acd515469668d87a3bbde064
34.934132
126
0.684719
4.530196
false
false
false
false
ochan1/OC-PublicCode
MakeSchoolNotes-Swift-V2-Starter-swift3-coredata TO-DO MOD copy/MakeSchoolNotes/Controllers/DisplayNoteViewController.swift
1
2679
// // DisplayNoteViewController.swift // MakeSchoolNotes // // Created by Chris Orcutt on 1/10/16. // Copyright © 2016 MakeSchool. All rights reserved. // import UIKit class DisplayNoteViewController: UIViewController { var note: Note? override func viewDidLoad() { super.viewDidLoad() } @IBOutlet weak var noteContentTextView: UITextView! @IBOutlet weak var noteTitleTextField: UITextField! @IBOutlet weak var noteCategoryTextField: UITextField! @IBOutlet weak var noteDueDateTextField: UITextField! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 1 if let note = note { // 2 noteTitleTextField.text = note.title noteContentTextView.text = note.content noteCategoryTextField.text = note.category noteDueDateTextField.text = note.dueDate } else { // 3 noteTitleTextField.text = "" noteContentTextView.text = "" noteCategoryTextField.text = "" noteDueDateTextField.text = "" } } /* override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { if identifier == "cancel" { print("Cancel button tapped") } else if identifier == "save" { print("Save button tapped") // 1 //let note = Note() let note = CoreDataHelper.newNote() // 2 note.title = "crash point" note.title = noteTitleTextField.text ?? "" //crash point note.content = noteContentTextView.text ?? "" // 3 note.modificationTime = Date() as NSDate } } } */ override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "save" { // if note exists, update title and content let note = self.note ?? CoreDataHelper.newNote() note.title = noteTitleTextField.text ?? "" note.content = noteContentTextView.text ?? "" note.category = noteCategoryTextField.text ?? "" note.dueDate = noteDueDateTextField.text ?? "" note.modificationTime = Date() as NSDate //"Date()" will be "optional" because not always perfect, meaning will create a "nil" since the data is not always there (esp when there are no Notes available, meaning need to be forced unwrapped CoreDataHelper.saveNote() } } }
mit
a60ebd022e3dbfefd67a03c4f4cf6124
32.898734
250
0.572816
5.005607
false
false
false
false
Caiflower/SwiftWeiBo
花菜微博/花菜微博/Classes/Tools(工具)/CFAddition(Swift)/UIKit/UIBarButtonItem-Addition.swift
1
1551
// // UIBarButtonItem-Extension.swift // 花菜微博 // // Created by 花菜ChrisCai on 2016/12/1. // Copyright © 2016年 花菜ChrisCai. All rights reserved. // import UIKit extension UIBarButtonItem { /// 自定义UIBarButtonItem构造器 /// /// - Parameters: /// - title: 标题 /// - fontSize: 文字大小,默认16 /// - target: target /// - action: action /// - isBack: 是否是返回按钮,如果是加上箭头 convenience init(title: String, fontSize: CGFloat = 16, target: AnyObject?,action: Selector, isBack: Bool = false) { let btn : UIButton = UIButton.cf_textButton(title, fontSize: fontSize, normalColor: UIColor.orange, highlightedColor: UIColor.orange) if isBack { let imageName = "navigationbar_back_withtext" btn.setImage(UIImage(named: imageName), for: .normal) btn.setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0) btn.sizeToFit() } btn.addTarget(target, action: action, for: .touchUpInside) self.init(customView:btn) } convenience init(imageName: String) { let btn = UIButton(); btn.setImage(UIImage(named: imageName), for: .normal) btn.setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) btn.sizeToFit() let view = UIView(frame: btn.bounds) self.init(customView:view) } }
apache-2.0
ddc4e5b7b340e031a524eda9035889d4
32.545455
141
0.614499
4.043836
false
false
false
false
Alexiuce/Tip-for-day
iFeiBo/Pods/Kingfisher/Sources/NSButton+Kingfisher.swift
6
15719
// // NSButton+Kingfisher.swift // Kingfisher // // Created by Jie Zhang on 14/04/2016. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import AppKit // MARK: - Set Images /** * Set image to use from web. */ extension Kingfisher where Base: NSButton { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. If `resource` is `nil`, the `placeholder` image will be set and `completionHandler` will be called with both `error` and `image` being `nil`. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.image = placeholder setWebURL(nil) completionHandler?(nil, nil, .none, nil) return .empty } let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo) if !options.keepCurrentImageWhileLoading { base.image = placeholder } setWebURL(resource.downloadURL) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL else { completionHandler?(image, error, cacheType, imageURL) return } self.setImageTask(nil) if image != nil { strongBase.image = image } completionHandler?(image, error, cacheType, imageURL) } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelImageDownloadTask() { imageTask?.cancel() } /** Set an alternateImage with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. If `resource` is `nil`, the `placeholder` image will be set and `completionHandler` will be called with both `error` and `image` being `nil`. */ @discardableResult public func setAlternateImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.alternateImage = placeholder setAlternateWebURL(nil) completionHandler?(nil, nil, .none, nil) return .empty } let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo) if !options.keepCurrentImageWhileLoading { base.alternateImage = placeholder } setAlternateWebURL(resource.downloadURL) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.alternateWebURL else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.alternateWebURL else { completionHandler?(image, error, cacheType, imageURL) return } self.setAlternateImageTask(nil) if image != nil { strongBase.alternateImage = image } completionHandler?(image, error, cacheType, imageURL) } }) setAlternateImageTask(task) return task } /// Cancel the alternate image download task bounded to the image view if it is running. /// Nothing will happen if the downloading has already finished. public func cancelAlternateImageDownloadTask() { alternateImageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var imageTaskKey: Void? private var lastAlternateURLKey: Void? private var alternateImageTaskKey: Void? extension Kingfisher where Base: NSButton { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL?) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Get the alternate image URL binded to this button. public var alternateWebURL: URL? { return objc_getAssociatedObject(base, &lastAlternateURLKey) as? URL } fileprivate func setAlternateWebURL(_ url: URL?) { objc_setAssociatedObject(base, &lastAlternateURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var alternateImageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &alternateImageTaskKey) as? RetrieveImageTask } fileprivate func setAlternateImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &alternateImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `kf` namespacing instead. */ extension NSButton { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.setImage` instead.", renamed: "kf.setImage") public func kf_setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.cancelImageDownloadTask` instead.", renamed: "kf.cancelImageDownloadTask") public func kf_cancelImageDownloadTask() { kf.cancelImageDownloadTask() } /** Set an alternateImage with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.setAlternateImage` instead.", renamed: "kf.setAlternateImage") public func kf_setAlternateImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setAlternateImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /// Cancel the alternate image download task bounded to the image view if it is running. /// Nothing will happen if the downloading has already finished. @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.cancelAlternateImageDownloadTask` instead.", renamed: "kf.cancelAlternateImageDownloadTask") public func kf_cancelAlternateImageDownloadTask() { kf.cancelAlternateImageDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.webURL` instead.", renamed: "kf.webURL") public var kf_webURL: URL? { return kf.webURL } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task)} /// Get the alternate image URL binded to this button. @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.alternateWebURL` instead.", renamed: "kf.alternateWebURL") public var kf_alternateWebURL: URL? { return kf.alternateWebURL } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.setAlternateWebURL") fileprivate func kf_setAlternateWebURL(_ url: URL) { kf.setAlternateWebURL(url) } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.alternateImageTask") fileprivate var kf_alternateImageTask: RetrieveImageTask? { return kf.alternateImageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setAlternateImageTask") fileprivate func kf_setAlternateImageTask(_ task: RetrieveImageTask?) { kf.setAlternateImageTask(task) } }
mit
97de45cf656238fe14056451f85e7c47
45.368732
125
0.650932
5.527075
false
false
false
false
cwaffles/Soulcast
to-be-integrated/RecordingVC.swift
1
2037
import UIKit class RecordingVC: UIViewController { var outgoingSoul:Soul? var recordingStartTime:NSDate! var soulRecorder = SoulRecorder() let soulPlayer = SoulPlayer() override func viewDidLoad() { super.viewDidLoad() configureAudio() } override func viewDidAppear(animated: Bool) { requestStartRecording() } func configureAudio() { soulRecorder.delegate = self soulRecorder.setup() do { try audioController.start() } catch { assert(false); print("audioController.start() error") } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RecordingVC.soulDidFailToPlay(_:)), name: "soulDidFailToPlay", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RecordingVC.soulDidFinishPlaying(_:)), name: "soulDidFinishPlaying", object: nil) } func requestStartRecording() { recordingStartTime = NSDate() soulRecorder.pleaseStartRecording() } func requestFinishRecording() { soulRecorder.pleaseStopRecording() } func playbackSoul(localSoul:Soul) { print("playbackSoul localSoul:\(localSoul)") soulPlayer.startPlaying(localSoul) } } extension RecordingVC: SoulRecorderDelegate { func soulDidStartRecording() { print("soulDidStartRecording") } func soulDidFailToRecord() { print("soulDidFailToRecord") } func soulDidReachMinimumDuration() { print("soulDidReachMinimumDuration") } func soulDidFinishRecording(newSoul: Soul) { print("soulDidFinishRecording") playbackSoul(newSoul) //TODO: mock and semi-real sending here... newSoul.printProperties() } } extension RecordingVC { func soulDidFailToPlay(notification:NSNotification) { let failSoul = notification.object as! Soul print(failSoul.description) } func soulDidFinishPlaying(notification:NSNotification) { let finishedSoul = notification.object as! Soul print(finishedSoul.description) } }
mit
ecc73949c8daf034a70830aa52cd911d
21.88764
160
0.707904
4.577528
false
false
false
false
niklassaers/SnapTagsView
SnapTagsView/SnapSearchBarController.swift
6
7484
import UIKit open class SnapSearchBarController : UIViewController { open lazy var sizer = SnapTextWidthSizers() open var configuration : SnapTagsViewConfiguration! open var buttonConfiguration : SnapTagButtonConfiguration! open var height : CGFloat = 36.0 fileprivate var tagScrollView : UIScrollView? fileprivate var searchTextField : UITextField? internal let tagsVc = SnapTagsCollectionViewController() fileprivate var searchBarInteractionEnabled = false open var placeholderText : String? { didSet { updatePlaceholder() } } fileprivate var placeholderTextRepresentation : String { get { if data.count == 0 { if let placeholderText = placeholderText { return placeholderText } else { return "Hva leter du etter?" } } else { return "" } } } open var searchBar : UISearchBar { get { return self.view as! UISearchBar } } open var data : [SnapTagRepresentation] { get { return tagsVc.data } set(value) { tagsVc.data = value updatePlaceholder() } } open var delegate : SnapTagsButtonDelegate? { get { return tagsVc.delegate } set(value) { tagsVc.delegate = value } } open override func viewDidLoad() { super.viewDidLoad() assert(configuration != nil) assert(buttonConfiguration != nil) configuration.alignment = .natural tagsVc.configuration = configuration tagsVc.buttonConfiguration = buttonConfiguration tagsVc.handlesViewConfigurationMargins = false searchBar.gestureRecognizers?.forEach { $0.cancelsTouchesInView = false } searchBar.delegate = self searchBar.setNeedsLayout() searchBar.layoutIfNeeded() searchBarInteractionEnabled = false var searchTextField_ : UITextField? = nil for firstLevelSubview in searchBar.subviews { for subview in firstLevelSubview.subviews { if let subview = subview as? UITextField { searchTextField_ = subview break } } } guard let searchTextField = searchTextField_ else { print("Could not find textfield in searchbar") return } searchTextField.leftViewMode = .never searchTextField.rightViewMode = .never searchTextField.textAlignment = .natural searchTextField.textColor = UIColor.black searchTextField.tintColor = UIColor.roseColor self.searchTextField = searchTextField let hMargin = configuration.horizontalMargin let vMargin = configuration.verticalMargin tagScrollView = SnapTagsHorizontalScrollView.setupTagScrollViewAsSubviewOf(searchBar, horizontalMargin: hMargin, verticalMargin: vMargin) self.addChildViewController(tagsVc) tagScrollView?.addSubview(tagsVc.view) var constraints = [NSLayoutConstraint]() let dict = ["self": tagsVc.view!, "super": tagScrollView!] constraints.append(NSLayoutConstraint(expressionFormat: "self.right = super.right", parameters: dict)) constraints.append(NSLayoutConstraint(expressionFormat: "self.bottom = super.bottom", parameters: dict)) tagScrollView?.addConstraints(constraints) tagsVc.scrollEnabled = false tagsVc.view.translatesAutoresizingMaskIntoConstraints = true var frame = tagsVc.view.frame frame.size.width = tagsVc.calculateContentSizeForTags(data).width frame.size.height = tagScrollView?.frame.height ?? 0.0 tagsVc.view.frame = frame searchBar.setNeedsLayout() searchBar.layoutIfNeeded() var textFieldFrame = searchTextField.frame textFieldFrame.size.height = 34 searchTextField.frame = textFieldFrame updatePlaceholder() searchBar.setNeedsLayout() searchBar.layoutIfNeeded() tagsVc.scrollEnabled = true } open func setFont(_ font: UIFont) { searchTextField?.font = font } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() //self.searchBar.layoutIfNeeded() //self.searchBar.layoutSubviews() let newHeight: CGFloat = self.height for subView in searchBar.subviews { for subsubView in subView.subviews { if let textField = subsubView as? UITextField { var currentTextFieldBounds = textField.bounds currentTextFieldBounds.size.height = newHeight textField.bounds = currentTextFieldBounds textField.borderStyle = UITextBorderStyle.roundedRect } } } } open func beginEditingWithSearch(_ text: String) { tagScrollView?.isHidden = true searchBarInteractionEnabled = true searchBar.text = text searchTextField?.becomeFirstResponder() } open func updateSearchString(_ text: String) { searchBar.text = text } open func updatePlaceholder() { searchBar.placeholder = placeholderTextRepresentation } open func endEditing(_ cancelled: Bool) -> String { tagScrollView?.isHidden = false searchBarInteractionEnabled = false searchBar.resignFirstResponder() searchTextField?.resignFirstResponder() let newText = searchBar.text ?? "" searchBar.text = "" if cancelled { let oldText = data.map { $0.tag }.joined(separator: " ") updatePlaceholder() delegate?.searchCompletedWithString?(oldText) return oldText } else { let newData = newText.components(separatedBy: " ").map { SnapTagRepresentation(tag: $0) } self.data = newData reloadData() updatePlaceholder() delegate?.searchCompletedWithString?(newText) return newText } } open func reloadData() { tagsVc.reloadData() delay(0.2) { if let sv = self.tagScrollView?.subviews.first?.subviews.first as? UIScrollView { let x = fmax(0.0, (sv.contentSize.width - sv.bounds.size.width)) sv.setContentOffset(CGPoint(x: x, y: 0), animated: true) } } } } extension SnapSearchBarController : UISearchBarDelegate { public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { return searchBarInteractionEnabled } public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { //searchBar.text = searchBar.text?.uppercaseString delegate?.searchTextChanged?(searchBar.text ?? "") } public func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) { } public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { let _ = endEditing(false) } public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { let _ = endEditing(true) } }
bsd-3-clause
fe3c2e1d68f62d5b9a1be30e93ac91ac
30.711864
145
0.612774
5.79257
false
true
false
false
sdkshredder/SocialMe
SocialMe/SocialMe/AboutMeTVCell.swift
1
2155
// // AboutMeTVCell.swift // SocialMe // // Created by Matt Duhamel on 6/2/15. // Copyright (c) 2015 new. All rights reserved. // import UIKit import Parse class AboutMeTVCell: UITableViewCell, UITextFieldDelegate { // @IBOutlet weak var aboutMeLabel: UILabel! @IBOutlet weak var editButton: UIButton! @IBOutlet weak var aboutMeTF: UITextField! @IBOutlet weak var aboutMeLabel: UILabel! @IBAction func editTouched(sender: UIButton) { if sender.titleLabel!.text == "Edit" { editButton.setTitle("Save", forState: .Normal) aboutMeTF.text = aboutMeLabel.text UIView.animateWithDuration(0.2, animations: { self.aboutMeTF.alpha = 1 self.aboutMeLabel.alpha = 0 }) } else { editButton.setTitle("Edit", forState: .Normal) aboutMeLabel.text = aboutMeTF.text saveText() UIView.animateWithDuration(0.2, animations: { self.aboutMeTF.alpha = 0 self.aboutMeLabel.alpha = 1 self.aboutMeTF.resignFirstResponder() }) } var info = [String : String]() info["value"] = aboutMeTF.text NSNotificationCenter.defaultCenter().postNotificationName("aboutMeNotification", object: nil) NSNotificationCenter.defaultCenter().postNotificationName("updateAboutMe", object: nil, userInfo: info) } func saveText() { let user = PFUser.currentUser() let attr = "aboutMe" user!.setObject(aboutMeTF.text!, forKey: attr) user!.saveInBackgroundWithBlock { (succeeded, error) -> Void in if error == nil { print("success saving about me for user \(user!.username)") } else { print("handle error") } } } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if (range.length + range.location > 300) { return false } return true } }
mit
e6cc0ae1ab543da1af79f56a9032aa73
31.651515
132
0.587007
4.842697
false
false
false
false
chronotruck/CTKFlagPhoneNumber
ExampleCocoapods/Example/TableViewController.swift
1
2298
// // TableViewController.swift // FlagPhoneNumber_Example // // Created by Aurelien on 24/12/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import FlagPhoneNumber class TableViewController: UITableViewController { @IBOutlet weak var firstPhoneNumberTextField: FPNTextField! @IBOutlet weak var secondPhoneNumberTextField: FPNTextField! var listController: FPNCountryListViewController = FPNCountryListViewController(style: .grouped) var repository: FPNCountryRepository = FPNCountryRepository() override func viewDidLoad() { super.viewDidLoad() title = "In Table View" tableView.delaysContentTouches = false firstPhoneNumberTextField.displayMode = .picker firstPhoneNumberTextField.delegate = self secondPhoneNumberTextField.displayMode = .list secondPhoneNumberTextField.delegate = self listController.setup(repository: secondPhoneNumberTextField.countryRepository) listController.didSelect = { [weak self] country in self?.secondPhoneNumberTextField.setFlag(countryCode: country.code) } } @objc func dismissCountries() { listController.dismiss(animated: true, completion: nil) } } extension TableViewController: FPNTextFieldDelegate { func fpnDisplayCountryList() { let navigationViewController = UINavigationController(rootViewController: listController) listController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(dismissCountries)) self.present(navigationViewController, animated: true, completion: nil) } func fpnDidValidatePhoneNumber(textField: FPNTextField, isValid: Bool) { textField.rightViewMode = .always textField.rightView = UIImageView(image: isValid ? #imageLiteral(resourceName: "success") : #imageLiteral(resourceName: "error")) print( isValid, textField.getFormattedPhoneNumber(format: .E164) ?? "E164: nil", textField.getFormattedPhoneNumber(format: .International) ?? "International: nil", textField.getFormattedPhoneNumber(format: .National) ?? "National: nil", textField.getFormattedPhoneNumber(format: .RFC3966) ?? "RFC3966: nil", textField.getRawPhoneNumber() ?? "Raw: nil" ) } func fpnDidSelectCountry(name: String, dialCode: String, code: String) { print(name, dialCode, code) } }
apache-2.0
570c8e91158d21e71be94907537378f8
31.352113
146
0.782325
4.153707
false
false
false
false
sumitjagdev/SJSwiftSideMenuController
Example/SJSwiftSideMenuController/AppDelegate.swift
1
3629
// // AppDelegate.swift // SJSwiftSideMenuController // // Created by Sumit Jagdev on 01/04/2017. // Copyright (c) 2017 Sumit Jagdev. All rights reserved. // import UIKit import SJSwiftSideMenuController @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // Override point for customization after application launch. let storyBoard = UIStoryboard(name: "Main", bundle: nil) let months = DateFormatter().monthSymbols let days = DateFormatter().weekdaySymbols let mainVC = SJSwiftSideMenuController() let sideVC_L : SideMenuController = (storyBoard.instantiateViewController(withIdentifier: "SideMenuController") as? SideMenuController)! sideVC_L.menuItems = months as NSArray? ?? NSArray() let sideVC_R : SideMenuController = (storyBoard.instantiateViewController(withIdentifier: "SideMenuController") as? SideMenuController)! sideVC_R.menuItems = days as NSArray? ?? NSArray() let rootVC = storyBoard.instantiateViewController(withIdentifier: "ViewController") as UIViewController SJSwiftSideMenuController.setUpNavigation(rootController: rootVC, leftMenuController: sideVC_L, rightMenuController: sideVC_R, leftMenuType: .SlideOver, rightMenuType: .SlideView) SJSwiftSideMenuController.enableSwipeGestureWithMenuSide(menuSide: .LEFT) SJSwiftSideMenuController.enableDimbackground = true SJSwiftSideMenuController.leftMenuWidth = 280 //======================================= self.window?.rootViewController = mainVC self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
22e8b54c80089f34dff08b062f670e15
46.12987
285
0.715073
5.643857
false
false
false
false
jemmons/BetterBasement
BetterBasement/MenuController.swift
1
1977
import UIKit @objc protocol AnimatingMenu{ var view:UIView! {get set} func setNeedsStatusBarAppearanceUpdate() func moveToOpenState() func moveToClosedState() } class MenuController : UIViewController, AnimatingMenu { @IBOutlet var backButton:UIButton! @IBOutlet var menuView:UIView! weak var storedSnapshot:UIView? init(coder aDecoder: NSCoder!){ super.init(coder: aDecoder) modalPresentationStyle = UIModalPresentationStyle.Custom self.transitioningDelegate = self } override func prefersStatusBarHidden()->Bool{ return true } @IBAction func screenshotTapped(sender: AnyObject) { dismissViewControllerAnimated(true, completion:nil) } func moveToOpenState(){ let newSnapshot = UIScreen.mainScreen().snapshotViewAfterScreenUpdates(false) var point = view.center point.x -= menuView.bounds.size.width newSnapshot.center = point addShadowToView(newSnapshot) view.insertSubview(newSnapshot, belowSubview:backButton) storedSnapshot?.removeFromSuperview() storedSnapshot = newSnapshot } func moveToClosedState(){ if let snapshot = storedSnapshot{ snapshot.center = view.center } } func addShadowToView(view:UIView){ view.layer.shadowColor = UIColor.blackColor().CGColor view.layer.shadowOpacity = 0.3 view.layer.shadowOffset = CGSize(width: 2, height: 0) view.layer.shadowRadius = 4.0 } } extension MenuController : UIViewControllerTransitioningDelegate{ func animationControllerForPresentedController(presented:UIViewController!, presentingController presenting:UIViewController!, sourceController source:UIViewController!) -> UIViewControllerAnimatedTransitioning!{ return MenuAnimationController(isPresenting: true) } func animationControllerForDismissedController(dismissed:UIViewController!) -> UIViewControllerAnimatedTransitioning!{ return MenuAnimationController(isPresenting: false) } }
bsd-2-clause
d60534b8d57aed83c48f733e9fea15a9
26.09589
214
0.756196
5.431319
false
false
false
false
nodes-ios/Serpent
Serpent/Serpent/Classes/Serpent.swift
2
9143
// // Serializable.swift // NOCore // // Created by Kasper Welner on 22/01/15. // Copyright (c) 2015 Nodes. All rights reserved. // import Foundation // MARK: - Serializable - public protocol Serializable: Decodable, Encodable, Keymappable {} // MARK: - Encodable - public protocol Encodable { func encodableRepresentation() -> NSCoding } // MARK: - Decodable - public protocol Decodable { init(dictionary:NSDictionary?) } public extension Decodable { static func array(_ source: Any?) -> [Self] { guard let source = source as? [NSDictionary] else { return [Self]() } return source.map { Self(dictionary: ($0)) } } } private struct DefaultKeyMappings { fileprivate static let mappings = [String : String]() } // MARK: - Keymappable - public protocol Keymappable {} public extension Keymappable { /** Maps the content of value for **key** in **dictionary** to generic type **T**, conforming to **Serializable** protocol. - parameter dictionary: An optional dictionary containing values which should be parsed. - parameter key: ValueForKey will be called on the dictionary to extract the value to be parsed - returns: A mapped object conforming to *Serializable*, or nil if parsing failed */ func mapped<T>(_ dictionary: NSDictionary?, key: String) -> T? where T:Decodable { // Ensure the dictionary is not nil guard let dict = dictionary else { return nil } // Get the value from the dictionary for our key let sourceOpt = dict[key] // Check if we have the correct type and return it if possible if sourceOpt != nil && sourceOpt is NSDictionary { return T(dictionary: (sourceOpt as! NSDictionary)) } return nil } /** Maps the content of value for **key** in **dictionary** to an array containing where elements is of generic type **T**, conforming to **Serializable** protocol. - parameter dictionary: An optional dictionary containing values which should be parsed. - parameter key: ValueForKey will be called on the dictionary to extract the value to be parsed. - returns: An array of mapped objects conforming to *Serializable*, or an empty array if parsing failed. */ func mapped<T>(_ dictionary: NSDictionary?, key: String) -> T? where T:Sequence, T.Iterator.Element: Decodable { // Ensure the dictionary is not nil and get the value from the dictionary for our key guard let dict = dictionary, let sourceOpt = dict[key] else { return nil } if sourceOpt is [NSDictionary] { let source = (sourceOpt as! [NSDictionary]) let finalArray = source.map { T.Iterator.Element.init(dictionary: $0) } as? T return finalArray } return nil } /** A generic mapping function that will try to parse primitive types from the provided dictionary. Currently supported types are `Int`, `Float`, `Double`, `Bool`, `Char` and `String`. The `key` parameter will be first used to check value in custom input key mappings and if no value is found, then `key` is used as the key to get the value stored in `dictionary`. - parameter dictionary: An optional dictionary containing values which should be parsed. - parameter key: The key which will be used to get the actual key from input key mappings or as the actual key for the value being parsed from the dictionary. - returns: The value of primitive type `T` or `nil` if parsing was unsuccessful. */ func mapped<T>(_ dictionary: NSDictionary?, key: String) -> T? { // Ensure the dictionary is not nil guard let dict = dictionary else { return nil } // Get the value from the dictionary for our key let sourceOpt = dict[key] // Figure out what type is the value we got and parse accordingly switch sourceOpt { case (is T): return (sourceOpt as! T) case (is String) where T.self is Int.Type: let source = (sourceOpt as! String) return Int(source) as? T case (is String) where T.self is Double.Type: let source = (sourceOpt as! String) return Double(source) as? T case (is NSString) where T.self is Bool.Type: let source = (sourceOpt as! NSString) return source.boolValue as? T case (is String) where T.self is Character.Type: let source = (sourceOpt as! String) return Character(source) as? T case (is NSNumber) where T.self is String.Type: let source = (sourceOpt as! NSNumber) return String(describing: source) as? T case (is Double) where T.self is Float.Type: let source = (sourceOpt as! Double) return Float(source) as? T default: return nil } } /** A generic mapping function that will try to parse an object of type `T` from the string value contained in the provided dictionary. The `key` parameter will be first used to check value in custom input key mappings and if no value is found, then `key` is used as the key to get the value stored in `dictionary`. - parameter dictionary: An optional dictionary containing the array which should be parsed. - parameter key: The key which will be used to get the actual key from input key mappings or as the actual key for the value being parsed from the dictionary. - returns: The value of type `T` or `nil` if parsing was unsuccessful. */ func mapped<T:StringInitializable>(_ dictionary: NSDictionary?, key: String) -> T? { if let dict = dictionary, let source = dict[key] as? String , source.isEmpty == false { return T.fromString(source) } return nil } /** A generic mapping function that will try to parse enumerations with raw value from the provided dictionary. This function internally uses a variant of the generic `mapped()` function used to parse primitive types, which means that only enums with raw value of primitive type are supported. The `key` parameter will be first used to check value in custom input key mappings and if no value is found, then `key` is used as the key to get the value stored in `dictionary`. - parameter dictionary: An optional dictionary containing values which should be parsed. - parameter key: The key which will be used to get the actual key from input key mappings or as the actual key for the value being parsed from the dictionary. - returns: The enumeration of enum type `T` or `nil` if parsing was unsuccessful or enumeration does not exist. */ func mapped<T:RawRepresentable>(_ dictionary: NSDictionary?, key: String) -> T? { guard let source: T.RawValue = self.mapped(dictionary, key: key) else { return nil } return T(rawValue: source) } /** A generic mapping function that will try to parse an array of enumerations with raw value from the array contained in the provided dictionary. The `key` parameter will be first used to check value in custom input key mappings and if no value is found, then `key` is used as the key to get the value stored in `dictionary`. - parameter dictionary: An optional dictionary containing the array which should be parsed. - parameter key: The key which will be used to get the actual key from input key mappings or as the actual key for the value being parsed from the dictionary. - returns: An array of enum type `T` or an empty array if parsing was unsuccessful. */ func mapped<T>(_ dictionary: NSDictionary?, key: String) -> T? where T:Sequence, T.Iterator.Element: RawRepresentable { if let dict = dictionary, let source = dict[key] as? [T.Iterator.Element.RawValue] { let finalArray = source.map { T.Iterator.Element.init(rawValue: $0)! } return (finalArray as! T) } return nil } /** A generic mapping function that will try to parse an object of type `T` from the hex string value contained in the provided dictionary. The `key` parameter will be first used to check value in custom input key mappings and if no value is found, then `key` is used as the key to get the value stored in `dictionary`. - parameter dictionary: An optional dictionary containing the array which should be parsed. - parameter key: The key which will be used to get the actual key from input key mappings or as the actual key for the value being parsed from the dictionary. - returns: The value of type `T` or `nil` if parsing was unsuccessful. */ func mapped<T: HexInitializable>(_ dictionary: NSDictionary?, key: String) -> T? { guard let dict = dictionary, let source = dict[key] else { return nil } if let hexString = source as? String , hexString.isEmpty == false { return T.fromHexString(hexString) } return source as? T } }
mit
f526f1d33d885f5d9a154e2b94b002ce
36.625514
165
0.665208
4.479667
false
false
false
false
YauheniYarotski/APOD
APOD/IAPHelper.swift
1
5771
// // IAPHelper.swift // APOD // // Created by Yauheni Yarotski on 8/17/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import StoreKit public typealias ProductIdentifier = String public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> () open class IAPHelper : NSObject { fileprivate let productIdentifiers: Set<ProductIdentifier> fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>() fileprivate var productsRequest: SKProductsRequest? fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler? static let kIAPHelperPurchaseNotification = "IAPHelperPurchaseNotification" static let kIAPHelperPurchaseFailedNotification = "IAPHelperPurchaseFailedNotification" public init(productIds: Set<ProductIdentifier>) { self.productIdentifiers = productIds for productIdentifier in productIds { let purchased = UserDefaults.standard.bool(forKey: productIdentifier) if purchased { purchasedProductIdentifiers.insert(productIdentifier) print("Previously purchased: \(productIdentifier)") } else { print("Not purchased: \(productIdentifier)") } } super.init() SKPaymentQueue.default().add(self) } } // MARK: - StoreKit API extension IAPHelper { public func requestProducts(_ completionHandler: @escaping ProductsRequestCompletionHandler) { productsRequest?.cancel() productsRequestCompletionHandler = completionHandler productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest!.delegate = self productsRequest!.start() } public func buyProduct(_ product: SKProduct) { print("Buying \(product.productIdentifier)...") let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool { return purchasedProductIdentifiers.contains(productIdentifier) } public class func canMakePayments() -> Bool { return true } public func restorePurchases() { SKPaymentQueue.default().restoreCompletedTransactions() } } // MARK: - SKProductsRequestDelegate extension IAPHelper: SKProductsRequestDelegate { public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let products = response.products productsRequestCompletionHandler?(true, products) clearRequestAndHandler() } public func request(_ request: SKRequest, didFailWithError error: Error) { print("Failed to load list of products.") print("Error: \(error.localizedDescription)") productsRequestCompletionHandler?(false, nil) clearRequestAndHandler() } fileprivate func clearRequestAndHandler() { productsRequest = nil productsRequestCompletionHandler = nil } } // MARK: - SKPaymentTransactionObserver extension IAPHelper: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch (transaction.transactionState) { case .purchased: completeTransaction(transaction) break case .failed: failedTransaction(transaction) break case .restored: restoreTransaction(transaction) break case .deferred: break case .purchasing: break } } } fileprivate func completeTransaction(_ transaction: SKPaymentTransaction) { print("completeTransaction...") deliverPurchaseNotificatioForIdentifier(transaction.payment.productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } fileprivate func restoreTransaction(_ transaction: SKPaymentTransaction) { guard let productIdentifier = transaction.original?.payment.productIdentifier else { return } print("restoreTransaction... \(productIdentifier)") deliverPurchaseNotificatioForIdentifier(productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } fileprivate func failedTransaction(_ transaction: SKPaymentTransaction?) { print("failedTransaction...") if let transaction = transaction { if transaction.error!._code != SKError.paymentCancelled.rawValue { print("Transaction Error: \(transaction.error?.localizedDescription)") } SKPaymentQueue.default().finishTransaction(transaction) } NotificationCenter.default.post(name: Notification.Name(rawValue: IAPHelper.kIAPHelperPurchaseFailedNotification), object: transaction) } fileprivate func deliverPurchaseNotificatioForIdentifier(_ identifier: String?) { guard let identifier = identifier else { return } purchasedProductIdentifiers.insert(identifier) UserDefaults.standard.set(true, forKey: identifier) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: IAPHelper.kIAPHelperPurchaseNotification), object: identifier) } public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { failedTransaction(nil) } }
mit
4405747e02323c5b3ebf78fcc11238d1
33.969697
143
0.679549
6.099366
false
false
false
false