repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
cp3hnu/Bricking
Bricking/Source/CPLayoutAttribute+OP.swift
1
7093
// // CPLayoutAttribute+OP.swift // Bricking // // Created by CP3 on 2017/7/1. // Copyright © 2017年 CP3. All rights reserved. // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif // MARK: - +-*/% public extension CPLayoutAttribute { static func + (left: CPLayoutAttribute, right: CGFloat) -> CPLayoutAttribute { return CPLayoutAttribute(view: left.view, attribute: left.attribute, multiplier: left.multiplier, constant: left.constant + right) } static func + (left: CGFloat, right: CPLayoutAttribute) -> CPLayoutAttribute { return right + left } static func - (left: CPLayoutAttribute, right: CGFloat) -> CPLayoutAttribute { return left + (-right) } static func * (left: CPLayoutAttribute, right: CGFloat) -> CPLayoutAttribute { return CPLayoutAttribute(view: left.view, attribute: left.attribute, multiplier: left.multiplier * right, constant: left.constant) } static func * (left: CGFloat, right: CPLayoutAttribute) -> CPLayoutAttribute { return right * left } static func / (left: CPLayoutAttribute, right: CGFloat) -> CPLayoutAttribute { return left * (1.0/right) } static func % (left: CGFloat, right: CPLayoutAttribute) -> CPLayoutAttribute { return right * (left/100.0) } } // MARK: - Relative to super constraints public extension CPLayoutAttribute { @discardableResult static func == (left: CPLayoutAttribute, right: CGFloat) -> NSLayoutConstraint? { return relativeToSuperView(left: left, relation: .equal, right: right) } @discardableResult static func >= (left: CPLayoutAttribute, right: CGFloat) -> NSLayoutConstraint? { return relativeToSuperView(left: left, relation: .greaterThanOrEqual, right: right) } @discardableResult static func <= (left: CPLayoutAttribute, right: CGFloat) -> NSLayoutConstraint? { return relativeToSuperView(left: left, relation: .lessThanOrEqual, right: right) } @discardableResult static func == (left: CPLayoutAttribute, right: PriorityConstant) -> NSLayoutConstraint? { return relativeToSuperView(left: left, relation: .equal, right: right.constant, priority: right.priority) } @discardableResult static func >= (left: CPLayoutAttribute, right: PriorityConstant) -> NSLayoutConstraint? { return relativeToSuperView(left: left, relation: .greaterThanOrEqual, right: right.constant, priority: right.priority) } @discardableResult static func <= (left: CPLayoutAttribute, right: PriorityConstant) -> NSLayoutConstraint? { return relativeToSuperView(left: left, relation: .lessThanOrEqual, right: right.constant, priority: right.priority) } static private func relativeToSuperView(left: CPLayoutAttribute, relation: LayoutRelation, right: CGFloat, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint? { let attribute = left.attribute var superview = left.view.superview if superview == nil && attribute != .width && attribute != .height { return nil } var constant = right if attribute == .width || attribute == .height { superview = nil } if attribute == .trailing || attribute == .bottom { constant = -right } let constraint = NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: relation, toItem: superview, attribute: attribute, multiplier: 1, constant: constant) constraint.priority = priority constraint.isActive = true return constraint } } // MARK: - Relative to other constraints public extension CPLayoutAttribute { @discardableResult static func == (left: CPLayoutAttribute, right: CPLayoutAttribute) -> NSLayoutConstraint? { return relativeToAttribute(left: left, relation: .equal, right: right) } @discardableResult static func >= (left: CPLayoutAttribute, right: CPLayoutAttribute) -> NSLayoutConstraint? { return relativeToAttribute(left: left, relation: .greaterThanOrEqual, right: right) } @discardableResult static func <= (left: CPLayoutAttribute, right: CPLayoutAttribute) -> NSLayoutConstraint? { return relativeToAttribute(left: left, relation: .lessThanOrEqual, right: right) } @discardableResult static func == (left: CPLayoutAttribute, right: PriorityAttribute) -> NSLayoutConstraint? { return relativeToAttribute(left: left, relation: .equal, right: right.attribute, priority: right.priority) } @discardableResult static func >= (left: CPLayoutAttribute, right: PriorityAttribute) -> NSLayoutConstraint? { return relativeToAttribute(left: left, relation: .greaterThanOrEqual, right: right.attribute, priority: right.priority) } @discardableResult static func <= (left: CPLayoutAttribute, right: PriorityAttribute) -> NSLayoutConstraint? { return relativeToAttribute(left: left, relation: .lessThanOrEqual, right: right.attribute, priority: right.priority) } static private func relativeToAttribute(left: CPLayoutAttribute, relation: LayoutRelation, right: CPLayoutAttribute, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint? { guard let _ = closestCommonAncestor(left.view, right.view) else { return nil } let constraint = NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: relation, toItem: right.view, attribute: right.attribute, multiplier: right.multiplier, constant: right.constant) constraint.priority = priority constraint.isActive = true return constraint } } private func closestCommonAncestor(_ a: View, _ b: View) -> View? { let (aSuper, bSuper) = (a.superview, b.superview) if a === b { return a } if a === bSuper { return a } if b === aSuper { return b } if aSuper === bSuper { return aSuper } let ancestorsOfA = Set(ancestors(a)) for ancestor in ancestors(b) { if ancestorsOfA.contains(ancestor) { return ancestor } } return .none } private func ancestors(_ v: View) -> AnySequence<View> { return AnySequence { () -> AnyIterator<View> in var view: View? = v return AnyIterator { let current = view view = view?.superview return current } } }
mit
9b915f5c0dd06064fa4941cb8b8e9bd6
38.388889
196
0.622003
5.086083
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Util/AnswersHelper.swift
1
2526
import Foundation // TODO add Fabric Answers class AnswersHelper { var TYPE_LINE_DETAILS = "LineDetails" var TYPE_BUS_DETAILS = "BusDetails" var TYPE_INTRO_ECO_POINTS = "IntroEcoPoints" var CATEGORY_ROUTE = "Route" var CATEGORY_DEPARTURES = "Departures" static func logProfileAction(action: String) { /*if (!BuildConfig.DEBUG) { var event = CustomEvent("EcoPointsProfile") .putCustomAttribute("Category", action) Answers.getInstance().logCustom(event) }*/ } static func logCustom(category: String, action: String) { /* if (!BuildConfig.DEBUG) { val event = CustomEvent(category) .putCustomAttribute("Action", action) Answers.getInstance().logCustom(event) }*/ } static func logSearch(category: String, query: String) { /* if (!BuildConfig.DEBUG) { val event = SearchEvent() .putCustomAttribute("Category", category) .putQuery(query) Answers.getInstance().logSearch(event) }*/ } static func logContentView(type: String, id: String) { /* if (!BuildConfig.DEBUG) { val event = ContentViewEvent() .putContentType(type) .putContentId(id) Answers.getInstance().logContentView(event) }*/ } static func logLoginSuccess(isGoogleSignIn: Bool) { /*if (!BuildConfig.DEBUG) { val event = LoginEvent() .putSuccess(true) .putMethod(if (isGoogleSignIn) "Google" else "Default") Answers.getInstance().logLogin(event)*/ } static func logLoginError(error: String) { /* if (!BuildConfig.DEBUG) { val event = LoginEvent() .putSuccess(false) .putCustomAttribute("Error", error) Answers.getInstance().logLogin(event) }*/ } static func logSignUpSuccess() { /*if (!BuildConfig.DEBUG) { val event = SignUpEvent() .putSuccess(true) Answers.getInstance().logSignUp(event) }*/ } static func logSignUpError(error: String) { /* if (!BuildConfig.DEBUG) { val event = SignUpEvent() .putSuccess(false) .putCustomAttribute("Error", error) Answers.getInstance().logSignUp(event) }*/ } }
gpl-3.0
e93aae4c080d983361d001cb12af67d2
26.758242
75
0.547506
4.518784
false
true
false
false
BoxJeon/funjcam-ios
Application/Application/Recent/View/RecentEmptyCell.swift
1
1072
import UIKit import TinyConstraints final class RecentEmptyCell: UICollectionViewListCell { private weak var emptyLabel: UILabel? override init(frame: CGRect) { super.init(frame: frame) let emptyLabel = UILabel() emptyLabel.text = Resource.string("search:noResult") self.contentView.addSubview(emptyLabel) emptyLabel.centerInSuperview() self.emptyLabel = emptyLabel } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { if let superViewSize = self.superview?.frame.size { let targetSize = superViewSize layoutAttributes.frame.size = self.contentView.systemLayoutSizeFitting( targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel ) return layoutAttributes } else { return super.preferredLayoutAttributesFitting(layoutAttributes) } } }
mit
3fbace8dacdc01d525771ac945d6d563
30.529412
140
0.73694
5.525773
false
false
false
false
valen90/scoreket
Sources/App/Models/Message.swift
1
2403
// // Message.swift // scoket // // Created by Valen on 28/03/2017. // // import Vapor import Fluent final class Message: Model { var id: Node? var game: Int var resultOne: Int var resultTwo: Int var scteam_id: Int init(game: Int, resultOne: Int, resultTwo: Int, scteam_id: Int)throws{ self.game = game self.resultOne = resultOne self.resultTwo = resultTwo self.scteam_id = scteam_id } init(node: Node, in context: Context) throws { id = try node.extract("id") game = try node.extract("game") resultOne = try node.extract("resultOne") resultTwo = try node.extract("resultTwo") scteam_id = try node.extract("team_id") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "game": game, "resultOne": resultOne, "resultTwo": resultTwo, "team_id": scteam_id ]) } func makeJSON() throws -> JSON { return try JSON(node: [ "id":id, "game": try Game.find(Node(game))?.makeJSON(), "resultOne": resultOne, "resultTwo": resultTwo, "team_id": try Team.find(Node(scteam_id))?.makeJSON() ]) } static func prepare(_ database: Database) throws { try database.create("messages"){ message in message.id() message.integer("game", signed: false) message.int("resultOne") message.int("resultTwo") message.integer("team_id", signed: false) } try database.foreign( parentTable: "teams", parentPrimaryKey: "id", childTable: "messages", childForeignKey: "team_id") try database.foreign( parentTable: "games", parentPrimaryKey: "id", childTable: "messages", childForeignKey: "game") } static func revert(_ database: Database) throws { try database.delete("messages") } } extension Message { func returnGame() throws -> Game { return try parent(Node(self.game),nil,Game.self).get()! } func returnTeam() throws -> Team? { return try parent(Node(self.scteam_id),nil,Team.self).get() } }
mit
51d40bc98c078fefcf94d6ee33eacdcc
25.119565
74
0.532251
3.998336
false
false
false
false
rambler-digital-solutions/rambler-it-ios
Carthage/Checkouts/rides-ios-sdk/source/UberRides/Model/RideMap.swift
1
1979
// // RideMap.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. 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. // MARK: RideMap /** * Visual representation of a ride request, only available after a request is accepted. */ @objc(UBSDKRideMap) public class RideMap: NSObject, Codable { /// URL to a map representing the requested trip. @objc public private(set) var path: URL /// Unique identifier representing a ride request. @objc public private(set) var requestID: String enum CodingKeys: String, CodingKey { case path = "href" case requestID = "request_id" } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) path = try container.decode(URL.self, forKey: .path) requestID = try container.decode(String.self, forKey: .requestID) } }
mit
0b0ed437542d501e4b1d16427d46f91b
40.208333
88
0.717391
4.328228
false
false
false
false
jayrparro/iOS11-Examples
Vision/ObjectTracker/ObjectTracker/ViewController.swift
1
5602
// // ViewController.swift // ObjectTracker // // import UIKit import AVFoundation import Vision // this is from https://github.com/jeffreybergier/Blog-Getting-Started-with-Vision class ViewController: UIViewController { @IBOutlet weak var cameraView: UIView! @IBOutlet weak var highlightView: UIView! { didSet { self.highlightView?.layer.borderColor = UIColor.red.cgColor self.highlightView?.layer.borderWidth = 4 self.highlightView?.backgroundColor = .clear } } private lazy var captureSession: AVCaptureSession = { let session = AVCaptureSession() session.sessionPreset = AVCaptureSession.Preset.photo guard let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back), let input = try? AVCaptureDeviceInput(device: backCamera) else { return session } session.addInput(input) return session }() private lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) private let visionSequenceHandler = VNSequenceRequestHandler() private var lastObservation: VNDetectedObjectObservation? override func viewDidLoad() { super.viewDidLoad() // hide the red focus area on load self.highlightView?.frame = .zero // make the camera appear on the screen self.cameraView?.layer.addSublayer(self.cameraLayer) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.userTapped(_:))) self.view.addGestureRecognizer(tapGesture) // register to receive buffers from the camera let videoOutput = AVCaptureVideoDataOutput() videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "MyQueue")) self.captureSession.addOutput(videoOutput) // begin the session self.captureSession.startRunning() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.cameraLayer.frame = self.cameraView?.bounds ?? .zero } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - UI Actions @objc private func userTapped(_ sender: UITapGestureRecognizer) { // get the center of the tap self.highlightView?.frame.size = CGSize(width: 120, height: 120) self.highlightView?.center = sender.location(in: self.view) // convert the rect for the initial observation let originalRect = self.highlightView?.frame ?? .zero var convertedRect = self.cameraLayer.metadataOutputRectConverted(fromLayerRect: originalRect) convertedRect.origin.y = 1 - convertedRect.origin.y // set the observation let newObservation = VNDetectedObjectObservation(boundingBox: convertedRect) self.lastObservation = newObservation } @IBAction private func resetTapped(_ sender: UIBarButtonItem) { self.lastObservation = nil self.highlightView?.frame = .zero } // MARK: - Private Methods private func handleVisionRequestUpdate(_ request: VNRequest, error: Error?) { // Dispatch to the main queue because we are touching non-atomic, non-thread safe properties of the view controller DispatchQueue.main.async { // make sure we have an actual result guard let newObservation = request.results?.first as? VNDetectedObjectObservation else { return } // prepare for next loop self.lastObservation = newObservation // check the confidence level before updating the UI guard newObservation.confidence >= 0.3 else { // hide the rectangle when we lose accuracy so the user knows something is wrong self.highlightView?.frame = .zero return } // calculate view rect var transformedRect = newObservation.boundingBox transformedRect.origin.y = 1 - transformedRect.origin.y let convertedRect = self.cameraLayer.layerRectConverted(fromMetadataOutputRect: transformedRect) // move the highlight view self.highlightView?.frame = convertedRect } } } // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate { func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard // make sure the pixel buffer can be converted let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer), // make sure that there is a previous observation we can feed into the request let lastObservation = self.lastObservation else { return } // create the request let request = VNTrackObjectRequest(detectedObjectObservation: lastObservation, completionHandler: self.handleVisionRequestUpdate) // set the accuracy to high // this is slower, but it works a lot better request.trackingLevel = .accurate // perform the request do { try self.visionSequenceHandler.perform([request], on: pixelBuffer) } catch { print("Throws: \(error)") } } }
mit
4d997027dd6ae176b42b619f0c03cb78
37.634483
137
0.65316
5.55754
false
false
false
false
okkhoury/SafeNights_iOS
SafeNights/Alcoholtable.swift
1
1584
import Foundation public class Alcoholtable { public var pk : Int? public var model : String? public var fields : Fields? /** Returns an array of models based on given dictionary. Sample usage: let alcoholtable_list = Alcoholtable.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of Alcoholtable Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [Alcoholtable] { var models:[Alcoholtable] = [] for item in array { models.append(Alcoholtable(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let alcoholtable = Alcoholtable(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: Alcoholtable Instance. */ required public init?(dictionary: NSDictionary) { pk = dictionary["pk"] as? Int model = dictionary["model"] as? String if (dictionary["fields"] != nil) { fields = Fields(dictionary: dictionary["fields"] as! NSDictionary) } } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.pk, forKey: "pk") dictionary.setValue(self.model, forKey: "model") dictionary.setValue(self.fields?.dictionaryRepresentation(), forKey: "fields") return dictionary } }
mit
ae9a4025c85f2c9920e1723c34ffa221
24.548387
105
0.695076
4.461972
false
false
false
false
lorismaz/LaDalle
LaDalle/LaDalle/BusinessTableViewController.swift
1
4868
// // BusinessTableViewController.swift // LaDalle // // Created by Loris Mazloum on 9/16/16. // Copyright © 2016 Loris Mazloum. All rights reserved. // import UIKit import CoreLocation class BusinessTableViewController: UITableViewController { // MARK: Variables var businesses = [Business]() var category: Category? var userLocation: CLLocation? //MARK: Outlets and Actions @IBOutlet weak var categoryNameLabel: UILabel! // MARK: App Functions override func viewDidLoad() { super.viewDidLoad() guard let currentCategory = self.category else { return } categoryNameLabel.text = currentCategory.title print(">>>let's do this>>>") self.tableView.backgroundView = UIImageView(image: UIImage(named: "o-2-blured")) self.tableView.backgroundView?.clipsToBounds = true reload() } //The Main OperationQueue is where any UI changes or updates happen private let main = OperationQueue.main //The Async OperationQueue is where any background tasks such as //Loading from the network, and parsing JSON happen. //This makes sure the Main UI stays sharp, responsive, and smooth private let async: OperationQueue = { //The Queue is being created by this closure let operationQueue = OperationQueue() //This represents how many tasks can run at the same time, in this case 8 tasks //That means that we can load 8 images at a time operationQueue.maxConcurrentOperationCount = 8 return operationQueue }() func reload() { async.addOperation { guard let currentCategory = self.category else { return } if let currentLocation = self.userLocation { print(currentCategory.alias) print(currentLocation) Business.getLocalPlaces(forCategory: currentCategory.alias, coordinates: currentLocation, completionHandler: { (business) in self.main.addOperation { //print("reload") self.businesses = business self.tableView.reloadData() } }) } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return businesses.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell let row = indexPath.row let business = businesses[row] cell.businessNameLabel.text = business.name async.addOperation { Business.getImageAsync(from: business.imageUrl, completionHandler: { (image) in self.main.addOperation { if (tableView.indexPathsForVisibleRows?.contains(indexPath) ?? false) { let animation = { cell.businessImageView.image = image } UIView.transition(with: cell.businessImageView, duration: 0.8, options: .transitionCrossDissolve, animations: animation, completion: nil) } } }) } return cell } // MARK: - Navigation override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = indexPath.row let business = businesses[row] displayBusiness(business: business) } func displayBusiness(business: Business) { performSegue(withIdentifier: "ToBusinessDetail", sender: business) } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // pass Business data if segue.identifier == "ToBusinessDetail" { guard let business = sender as? Business else { return } guard let businessDetailViewController = segue.destination as? BusinessDetailsViewController else { return } businessDetailViewController.business = business businessDetailViewController.userLocation = self.userLocation } } }
mit
dd884fd0fc0c05d1d8f00aa8553fa7f1
31.446667
161
0.584754
5.885127
false
false
false
false
Leo19/swift_begin
test-swift/FirstLesson/FirstLesson/ViewController.swift
1
1110
// // ViewController.swift // FirstLesson // // Created by liushun on 15/9/6. // Copyright (c) 2015年 liushun. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var text1: UITextField! @IBOutlet weak var text2: UITextField! @IBOutlet var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.text1.text = "中文文本框内容实验"; println("what is this poem") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didClicked(sender: UIButton) { var countResult = 0 println("button clicked!") println(self.text1.text) // String xxx var val1 = self.text1.text.toInt() var val2 = self.text2.text.toInt() countResult = val1! + val2! println("result = \(countResult)") self.resultLabel.text = "\(countResult)" } }
gpl-2.0
74fa0ce64df5797485b931494fa09394
26.25
80
0.633945
4.097744
false
false
false
false
OrdnanceSurvey/search-swift
OSSearch/GazetteerEntry.swift
1
10361
// // GazetteerEntry.swift // // // Created by Dave Hardiman on 11/04/2016 // Copyright (c) Ordnance Survey. All rights reserved. // import Foundation import OSJSON @objc(OSGazetteerEntry) public class GazetteerEntry: NSObject, Decodable { // MARK: Properties public let id: String public let namesUri: String public let name1: String public let name1Lang: String? public let name2: String? public let name2Lang: String? public let type: String public let localType: String public let geometryX: Double public let geometryY: Double public let mostDetailViewRes: Int public let leastDetailViewRes: Int public let mbrXmin: Double public let mbrYmin: Double public let mbrXmax: Double public let mbrYmax: Double public let postcodeDistrict: String? public let postcodeDistrictUri: String? public let populatedPlace: String? public let populatedPlaceUri: String? public let populatedPlaceType: String? public let districtBorough: String? public let districtBoroughUri: String? public let districtBoroughType: String? public let countyUnitary: String? public let countyUnitaryUri: String? public let countyUnitaryType: String? public let region: String public let regionUri: String public let country: String public let countryUri: String public let relatedSpatialObject: String? public let sameAsGeonames: String? public let sameAsDbpedia: String? init(id: String, namesUri: String, name1: String, name1Lang: String?, name2: String?, name2Lang: String?, type: String, localType: String, geometryX: Double, geometryY: Double, mostDetailViewRes: Int, leastDetailViewRes: Int, mbrXmin: Double, mbrYmin: Double, mbrXmax: Double, mbrYmax: Double, postcodeDistrict: String?, postcodeDistrictUri: String?, populatedPlace: String?, populatedPlaceUri: String?, populatedPlaceType: String?, districtBorough: String?, districtBoroughUri: String?, districtBoroughType: String?, countyUnitary: String?, countyUnitaryUri: String?, countyUnitaryType: String?, region: String, regionUri: String, country: String, countryUri: String, relatedSpatialObject: String?, sameAsGeonames: String?, sameAsDbpedia: String?) { self.id = id self.namesUri = namesUri self.name1 = name1 self.name1Lang = name1Lang self.name2 = name2 self.name2Lang = name2Lang self.type = type self.localType = localType self.geometryX = geometryX self.geometryY = geometryY self.mostDetailViewRes = mostDetailViewRes self.leastDetailViewRes = leastDetailViewRes self.mbrXmin = mbrXmin self.mbrYmin = mbrYmin self.mbrXmax = mbrXmax self.mbrYmax = mbrYmax self.postcodeDistrict = postcodeDistrict self.postcodeDistrictUri = postcodeDistrictUri self.populatedPlace = populatedPlace self.populatedPlaceUri = populatedPlaceUri self.populatedPlaceType = populatedPlaceType self.districtBorough = districtBorough self.districtBoroughUri = districtBoroughUri self.districtBoroughType = districtBoroughType self.countyUnitary = countyUnitary self.countyUnitaryUri = countyUnitaryUri self.countyUnitaryType = countyUnitaryType self.region = region self.regionUri = regionUri self.country = country self.countryUri = countryUri self.relatedSpatialObject = relatedSpatialObject self.sameAsGeonames = sameAsGeonames self.sameAsDbpedia = sameAsDbpedia } //MARK: JSON initialiser convenience required public init?(json: JSON) { guard let gaz = json.jsonForKey(GazetteerEntry.GazetteerEntryKey), id = gaz.stringValueForKey(GazetteerEntry.IdKey), namesUri = gaz.stringValueForKey(GazetteerEntry.NamesUriKey), name1 = gaz.stringValueForKey(GazetteerEntry.Name1Key), type = gaz.stringValueForKey(GazetteerEntry.TypeKey), localType = gaz.stringValueForKey(GazetteerEntry.LocalTypeKey), region = gaz.stringValueForKey(GazetteerEntry.RegionKey), regionUri = gaz.stringValueForKey(GazetteerEntry.RegionUriKey), country = gaz.stringValueForKey(GazetteerEntry.CountryKey), countryUri = gaz.stringValueForKey(GazetteerEntry.CountryUriKey) else { return nil } let name1Lang = gaz.stringValueForKey(GazetteerEntry.Name1LangKey) let name2 = gaz.stringValueForKey(GazetteerEntry.Name2Key) let name2Lang = gaz.stringValueForKey(GazetteerEntry.Name2LangKey) let mostDetailViewRes = gaz.intValueForKey(GazetteerEntry.MostDetailViewResKey) let leastDetailViewRes = gaz.intValueForKey(GazetteerEntry.LeastDetailViewResKey) let geometryX = gaz.doubleValueForKey(GazetteerEntry.GeometryXKey) let geometryY = gaz.doubleValueForKey(GazetteerEntry.GeometryYKey) let mbrXmin = gaz.doubleValueForKey(GazetteerEntry.MbrXminKey) let mbrYmin = gaz.doubleValueForKey(GazetteerEntry.MbrYminKey) let mbrXmax = gaz.doubleValueForKey(GazetteerEntry.MbrXmaxKey) let mbrYmax = gaz.doubleValueForKey(GazetteerEntry.MbrYmaxKey) let postcodeDistrict = gaz.stringValueForKey(GazetteerEntry.PostcodeDistrictKey) let postcodeDistrictUri = gaz.stringValueForKey(GazetteerEntry.PostcodeDistrictUriKey) let populatedPlace = gaz.stringValueForKey(GazetteerEntry.PopulatedPlaceKey) let populatedPlaceUri = gaz.stringValueForKey(GazetteerEntry.PopulatedPlaceUriKey) let populatedPlaceType = gaz.stringValueForKey(GazetteerEntry.PopulatedPlaceTypeKey) let districtBorough = gaz.stringValueForKey(GazetteerEntry.DistrictBoroughKey) let districtBoroughUri = gaz.stringValueForKey(GazetteerEntry.DistrictBoroughUriKey) let districtBoroughType = gaz.stringValueForKey(GazetteerEntry.DistrictBoroughTypeKey) let countyUnitary = gaz.stringValueForKey(GazetteerEntry.CountyUnitaryKey) let countyUnitaryUri = gaz.stringValueForKey(GazetteerEntry.CountyUnitaryUriKey) let countyUnitaryType = gaz.stringValueForKey(GazetteerEntry.CountyUnitaryTypeKey) let relatedSpatialObject = gaz.stringValueForKey(GazetteerEntry.RelatedSpatialObjectKey) let sameAsGeonames = gaz.stringValueForKey(GazetteerEntry.SameAsGeonamesKey) let sameAsDbpedia = gaz.stringValueForKey(GazetteerEntry.SameAsDbpediaKey) self.init( id: id, namesUri: namesUri, name1: name1, name1Lang: name1Lang, name2: name2, name2Lang: name2Lang, type: type, localType: localType, geometryX: geometryX, geometryY: geometryY, mostDetailViewRes: mostDetailViewRes, leastDetailViewRes: leastDetailViewRes, mbrXmin: mbrXmin, mbrYmin: mbrYmin, mbrXmax: mbrXmax, mbrYmax: mbrYmax, postcodeDistrict: postcodeDistrict, postcodeDistrictUri: postcodeDistrictUri, populatedPlace: populatedPlace, populatedPlaceUri: populatedPlaceUri, populatedPlaceType: populatedPlaceType, districtBorough: districtBorough, districtBoroughUri: districtBoroughUri, districtBoroughType: districtBoroughType, countyUnitary: countyUnitary, countyUnitaryUri: countyUnitaryUri, countyUnitaryType: countyUnitaryType, region: region, regionUri: regionUri, country: country, countryUri: countryUri, relatedSpatialObject: relatedSpatialObject, sameAsGeonames: sameAsGeonames, sameAsDbpedia: sameAsDbpedia ) } } extension GazetteerEntry { // MARK: Declaration for string constants to be used to decode and also serialize. @nonobjc internal static let GazetteerEntryKey = "GAZETTEER_ENTRY" @nonobjc internal static let GeometryYKey = "GEOMETRY_Y" @nonobjc internal static let CountryKey = "COUNTRY" @nonobjc internal static let CountyUnitaryKey = "COUNTY_UNITARY" @nonobjc internal static let MbrYmaxKey = "MBR_YMAX" @nonobjc internal static let Name1Key = "NAME1" @nonobjc internal static let IdKey = "ID" @nonobjc internal static let CountyUnitaryTypeKey = "COUNTY_UNITARY_TYPE" @nonobjc internal static let TypeKey = "TYPE" @nonobjc internal static let PopulatedPlaceTypeKey = "POPULATED_PLACE_TYPE" @nonobjc internal static let CountyUnitaryUriKey = "COUNTY_UNITARY_URI" @nonobjc internal static let MbrYminKey = "MBR_YMIN" @nonobjc internal static let NamesUriKey = "NAMES_URI" @nonobjc internal static let RegionKey = "REGION" @nonobjc internal static let GeometryXKey = "GEOMETRY_X" @nonobjc internal static let MbrXminKey = "MBR_XMIN" @nonobjc internal static let LeastDetailViewResKey = "LEAST_DETAIL_VIEW_RES" @nonobjc internal static let MbrXmaxKey = "MBR_XMAX" @nonobjc internal static let PopulatedPlaceKey = "POPULATED_PLACE" @nonobjc internal static let PostcodeDistrictUriKey = "POSTCODE_DISTRICT_URI" @nonobjc internal static let RegionUriKey = "REGION_URI" @nonobjc internal static let CountryUriKey = "COUNTRY_URI" @nonobjc internal static let LocalTypeKey = "LOCAL_TYPE" @nonobjc internal static let PopulatedPlaceUriKey = "POPULATED_PLACE_URI" @nonobjc internal static let MostDetailViewResKey = "MOST_DETAIL_VIEW_RES" @nonobjc internal static let PostcodeDistrictKey = "POSTCODE_DISTRICT" @nonobjc internal static let Name1LangKey = "NAME1_LANG" @nonobjc internal static let Name2Key = "NAME2" @nonobjc internal static let Name2LangKey = "NAME2_LANG" @nonobjc internal static let DistrictBoroughKey = "DISTRICT_BOROUGH" @nonobjc internal static let DistrictBoroughUriKey = "DISTRICT_BOROUGH_URI" @nonobjc internal static let DistrictBoroughTypeKey = "DISTRICT_BOROUGH_TYPE" @nonobjc internal static let RelatedSpatialObjectKey = "RELATED_SPATIAL_OBJECT" @nonobjc internal static let SameAsGeonamesKey = "SAME_AS_GEONAMES" @nonobjc internal static let SameAsDbpediaKey = "SAME_AS_DBPEDIA" }
apache-2.0
1f086ca15ca21f92f0cc74e5eb1bb2de
49.296117
754
0.72271
3.914243
false
false
false
false
michaelvu812/MVMacros
MVMacros/MVMacros.swift
2
7264
// // MVMacros.swift // MVMacros // // Created by Michael on 25/6/14. // Copyright (c) 2014 Michael Vu. All rights reserved. // import Foundation import UIKit let MVDeviceIphone = "iPhone" let MVDeviceIpad = "iPad" let MVDeviceIpod = "iPod" let MVDeviceSimulator = "Simulator" let MVCurrentDevice = UIDevice.currentDevice() let MVDeviceMode = MVCurrentDevice.model let MVDeviceModeLocalized = MVCurrentDevice.localizedModel let MVDeviceName = MVCurrentDevice.name let MVDeviceOrientation = MVCurrentDevice.orientation let MVDeviceOrientationIsPortrait = UIInterfaceOrientationIsPortrait(MVSharedApplication.statusBarOrientation) let MVDeviceOrientationIsLandscape = UIInterfaceOrientationIsLandscape(MVSharedApplication.statusBarOrientation) let MVIsSimulator = TARGET_IPHONE_SIMULATOR let MVIsIPad = MVCurrentDevice.userInterfaceIdiom == .Pad let MVIsIPhone = MVCurrentDevice.userInterfaceIdiom == .Phone let MVIsIPhone5 = MVIsIPhone && CGSizeEqualToSize(MVMainScreen.preferredMode.size, CGSizeMake(640, 1136)) let MVIsRetina = MVMainScreen?.scale && MVMainScreen.scale == 2 let MVSystemVersionEqualTo: (String) -> (Bool) = {(version:String) -> Bool in MVCurrentDevice.systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch, range: nil, locale: nil) == NSComparisonResult.OrderedSame} let MVSystemVersionGreaterThan: (String) -> (Bool) = {(version:String) -> Bool in MVCurrentDevice.systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch, range: nil, locale: nil) == NSComparisonResult.OrderedDescending} let MVSystemVersionGreaterThanOrEqualTo: (String) -> (Bool) = {(version:String) -> Bool in MVCurrentDevice.systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch, range: nil, locale: nil) != NSComparisonResult.OrderedAscending} let MVSystemVersionLessThan: (String) -> (Bool) = {(version:String) -> Bool in MVCurrentDevice.systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch, range: nil, locale: nil) == NSComparisonResult.OrderedAscending} let MVSystemVersionLessThanOrEqualTo: (String) -> (Bool) = {(version:String) -> Bool in MVCurrentDevice.systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch, range: nil, locale: nil) != NSComparisonResult.OrderedDescending} let MVSharedApplication = UIApplication.sharedApplication() let MVApplicationDelegate = MVSharedApplication.delegate as AppDelegate let MVUserDefaults = NSUserDefaults.standardUserDefaults() let MVNotificationCenter = NSNotificationCenter.defaultCenter() let MVBundle = NSBundle.mainBundle() let MVMainScreen = UIScreen.mainScreen() let MVWindow = MVApplicationDelegate.window! let MVNetworkActivityIndicatorVisible: (Bool) -> () = {(isVisible:Bool) -> Void in MVSharedApplication.networkActivityIndicatorVisible = isVisible } let MVShowNetworkActivityIndicator = { MVNetworkActivityIndicatorVisible(true) } let MVHideNetworkActivityIndicator = { MVNetworkActivityIndicatorVisible(false) } let MVNavigationController = MVWindow.rootViewController ? (MVWindow.rootViewController.isKindOfClass(UINavigationController.classForCoder()) ? MVWindow.rootViewController as UINavigationController : MVWindow.rootViewController.navigationController) : nil let MVNavigationBar = MVNavigationController!.navigationBar let MVNavigationBarHeight = MVNavigationBar!.bounds.size.height let MVTabBarController = MVWindow.rootViewController ? (MVWindow.rootViewController.isKindOfClass(UITabBarController.classForCoder()) ? MVWindow.rootViewController as UITabBarController : MVWindow.rootViewController.tabBarController) : nil let MVTabBar = MVTabBarController!.tabBar let MVTabBarHeight = MVTabBar!.bounds.size.height let MVScreenWidth = MVMainScreen.bounds.size.width let MVScreenHeight = MVMainScreen.bounds.size.height let MVTouchHeightDefault = 44 let MVTouchHeightSmall = 32 let MVRectX: (CGRect) -> (CFloat) = {(frame:CGRect) -> CFloat in frame.origin.x } let MVRectY: (CGRect) -> (CFloat) = {(frame:CGRect) -> CFloat in frame.origin.y } let MVRectWidth: (CGRect) -> (CFloat) = {(frame:CGRect) -> CFloat in frame.size.width } let MVRectHeight: (CGRect) -> (CFloat) = {(frame:CGRect) -> CFloat in frame.size.height } let MVWidthOfView: (UIView) -> (CFloat) = {(view:UIView) -> CFloat in MVRectWidth(view.frame) } let MVHeightOfView: (UIView) -> (CFloat) = {(view:UIView) -> CFloat in MVRectHeight(view.frame) } let MVXOfView: (UIView) -> (CFloat) = {(view:UIView) -> CFloat in MVRectX(view.frame) } let MVYOfView: (UIView) -> (CFloat) = {(view:UIView) -> CFloat in MVRectY(view.frame) } let MVRectSetWidth: (CGRect, CFloat) -> (CGRect) = {(frame:CGRect, width:CFloat) -> CGRect in CGRectMake(MVRectX(frame), MVRectY(frame), width, MVRectHeight(frame))} let MVRectSetHeight: (CGRect, CFloat) -> (CGRect) = {(frame:CGRect, height:CFloat) -> CGRect in CGRectMake(MVRectX(frame), MVRectY(frame), MVRectWidth(frame), height)} let MVRectSetX: (CGRect, CFloat) -> (CGRect) = {(frame:CGRect, x:CFloat) -> CGRect in CGRectMake(x, MVRectY(frame), MVRectWidth(frame), MVRectHeight(frame))} let MVRectSetY: (CGRect, CFloat) -> (CGRect) = {(frame:CGRect, y:CFloat) -> CGRect in CGRectMake(MVRectX(frame), y, MVRectWidth(frame), MVRectHeight(frame))} let MVDate_Components:NSCalendarUnit = .YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit let MVTime_Components:NSCalendarUnit = .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit let MVDegreesToRadians: (CFloat) -> (CFloat) = {(angle:CFloat) -> CFloat in (angle / 180.0 * CFloat(M_PI))} let MVRGBA:(CFloat, CFloat, CFloat, CFloat) -> (UIColor) = {(red:CFloat, green:CFloat, blue:CFloat, alpha:CFloat) -> UIColor in UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha:alpha)} let MVRGB:(CFloat, CFloat, CFloat) -> (UIColor) = {(red:CFloat, green:CFloat, blue:CFloat) -> UIColor in MVRGBA(red, green, blue, 1.0)} let MVHexColor: (UInt32) -> (UIColor) = {(hex:UInt32) -> UIColor in MVRGBA(Float(Float((hex >> 16) & 0xFF)/255.0), Float(Float((hex >> 8) & 0xFF)/255.0), Float(Float(hex & 0xFF)/255.0), 1.0)} let MVAddObserver: (AnyObject?, Selector, String?, AnyObject?) -> () = {(observer:AnyObject?, selector:Selector, name:String?, object:AnyObject?) -> Void in MVNotificationCenter.addObserver(observer!, selector: selector, name: name!, object: object!)} let MVRemoveObserver: (AnyObject?) -> () = {(observer:AnyObject?) -> Void in MVNotificationCenter.removeObserver(observer!)} let MVNotify:(String?, AnyObject?, NSDictionary?) -> () = {(name:String?, object:AnyObject?, dictionary:NSDictionary?) -> Void in MVNotificationCenter.postNotificationName(name!, object: object!, userInfo: dictionary!)} let MVRunOnMainThread: (()?) -> () = {(block:()?) -> Void in if NSThread.isMainThread() { block! } else { dispatch_async(dispatch_get_main_queue(), { block! }) } } let MVInvalidateTimer: (NSTimer) -> () = {(var timer:NSTimer) -> Void in timer.invalidate();timer=NSTimer()} let MVQuickError: (Int, String, String?) -> (NSError) = {(code:Int, description:String, domain:String?) -> NSError in NSError(domain: domain!, code: code, userInfo: NSDictionary(object: description, forKey: NSLocalizedDescriptionKey))} func MVLogger(object:AnyObject, name:String = __FUNCTION__) {println("\(name) \(object.description)")}
mit
c8af87a506f205d8cc44d0c14fc233dc
93.350649
255
0.770512
4.053571
false
false
false
false
dangthaison91/SwagGen
Templates/Swift/request.swift
1
8851
{% include "Includes/header.stencil" %} import Foundation import JSONUtilities extension {{ options.name }}{% if tag %}.{{ options.tagPrefix }}{{ tag|upperCamelCase }}{{ options.tagSuffix }}{% endif %} { {% if description %} /** {{ description }} */ {% endif %} public enum {{ operationId|upperCamelCase }} { public static let service = APIService<Response>(id: "{{ operationId }}", tag: "{{ tag }}", method: "{{ method|uppercase }}", path: "{{ path }}", hasBody: {% if hasBody %}true{% else %}false{% endif %}{% if securityRequirement %}, authorization: Authorization(type: "{{ securityRequirement.name }}", scope: "{{ securityRequirement.scope }}"){% endif %}) {% for enum in enums %} {% if not enum.isGlobal %} {% include "Includes/enum.stencil" using enum %} {% endif %} {% endfor %} {% if bodyParam.anonymousSchema %} {% include "Includes/Model.stencil" using bodyParam %} {% endif %} public class Request: APIRequest<Response> { {% if nonBodyParams %} public struct Options { {% for param in nonBodyParams %} {% if param.description %} /** {{ param.description }} */ {% endif %} public var {{ param.name }}: {{ param.optionalType }} {% endfor %} public init({% for param in nonBodyParams %}{{param.name}}: {{param.optionalType}}{% ifnot param.required %} = nil{% endif %}{% ifnot forloop.last %}, {% endif %}{% endfor %}) { {% for param in nonBodyParams %} self.{{param.name}} = {{param.name}} {% endfor %} } } public var options: Options {% endif %} {% if bodyParam %} public var {{ bodyParam.name}}: {{bodyParam.optionalType}} {% endif %} public init({% if bodyParam %}{{ bodyParam.name}}: {{ bodyParam.optionalType }}{% if nonBodyParams %}, {% endif %}{% endif %}{% if nonBodyParams %}options: Options{% endif %}) { {% if bodyParam %} self.{{ bodyParam.name}} = {{ bodyParam.name}} {% endif %} {% if nonBodyParams %} self.options = options {% endif %} super.init(service: {{ operationId|upperCamelCase }}.service) } {% if nonBodyParams %} /// convenience initialiser so an Option doesn't have to be created public convenience init({% for param in params %}{{ param.name }}: {{ param.optionalType }}{% ifnot param.required %} = nil{% endif %}{% ifnot forloop.last %}, {% endif %}{% endfor %}) { {% if nonBodyParams %} let options = Options({% for param in nonBodyParams %}{{param.name}}: {{param.name}}{% ifnot forloop.last %}, {% endif %}{% endfor %}) {% endif %} self.init({% if bodyParam %}{{ bodyParam.name}}: {{ bodyParam.name}}{% if nonBodyParams %}, {% endif %}{% endif %}{% if nonBodyParams %}options: options{% endif %}) } {% endif %} {% if pathParams %} public override var path: String { return super.path{% for param in pathParams %}.replacingOccurrences(of: "{" + "{{ param.name }}" + "}", with: "\(self.options.{{ param.encodedValue }})"){% endfor %} } {% endif %} {% if encodedParams %} public override var parameters: [String: Any] { var params: JSONDictionary = [:] {% for param in encodedParams %} {% if param.optional %} if let {{ param.name }} = options.{{ param.encodedValue }} { params["{{ param.value }}"] = {{ param.name }} } {% else %} params["{{ param.value }}"] = options.{{ param.encodedValue }} {% endif %} {% endfor %} return params } {% endif %} {% if bodyParam %} public override var jsonBody: Any? { return {{ bodyParam.encodedValue }} } {% endif %} } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = {{ successType|default:"Void"}} {% for response in responses %} {% if response.description %} /** {{ response.description }} */ {% endif %} {% if response.statusCode %} case {{ response.name }}{% if response.type %}({{ response.type }}){% endif %} {% else %} case {{ response.name }}(statusCode: Int{% if response.type %}, {{ response.type }}{% endif %}) {% endif %} {% endfor %} public var success: {{ successType|default:"Void"}}? { switch self { {% for response in responses where response.type == successType and response.success %} case .{{ response.name }}({% if not response.statusCode %}_, {% endif %}let response): return response {% endfor %} default: return nil } } {% if singleFailureType %} public var failure: {{ singleFailureType }}? { switch self { {% for response in responses where response.type == singleFailureType and not response.success %} case .{{ response.name }}({% if not response.statusCode %}_, {% endif %}let response): return response {% endfor %} default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<{{ successType|default:"Void"}}, {{ singleFailureType }}> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } {% endif %} public var response: Any { switch self { {% for response in responses where response.type %} case .{{ response.name }}({% if not response.statusCode %}_, {% endif %}let response): return response {% endfor %} {% if not alwaysHasResponseType %} default: return () {% endif %} } } public var statusCode: Int { switch self { {% for response in responses %} {% if response.statusCode %} case .{{ response.name }}: return {{ response.statusCode }} {% else %} case .{{ response.name }}(let statusCode, _): return statusCode {% endif %} {% endfor %} } } public var successful: Bool { switch self { {% for response in responses %} case .{{ response.name }}: return {{ response.success }} {% endfor %} } } public init(statusCode: Int, data: Data) throws { switch statusCode { {% for response in responses where response.statusCode %} {% if response.type %} case {{ response.statusCode }}: self = try .{{ response.name }}(JSONDecoder.decode(data: data)) {% else %} case {{ response.statusCode }}: self = .{{ response.name }} {% endif %} {% endfor %} {% if defaultResponse %} {% if defaultResponse.type %} default: self = try .{{ defaultResponse.name }}(statusCode: statusCode, JSONDecoder.decode(data: data)) {% else %} default: self = .{{ defaultResponse.name }}(statusCode: statusCode) {% endif %} {% else %} default: throw APIError.unexpectedStatusCode(statusCode: statusCode, data: data) {% endif %} } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
mit
3ca185a1cbf29e1901278a87f6b319b3
40.947867
359
0.490792
5.3
false
false
false
false
Atsumi3/NKLineView
NKLineViewDemo/NKLineView/NKLineView.swift
1
3158
// // NKLineView.swift // NKLineViewDemo // // Created by Atsumi3 on 2016/02/26. // Copyright © 2016年 Atsumi3. All rights reserved. // import UIKit class NKLineView: UIView { ////// Property private var strokeWidth : CGFloat = 12; private var strokeColor : UIColor = UIColor.blueColor(); private var dashPattern : [CGFloat] { get { return [strokeWidth * 0, strokeWidth * 2]; } } private var leftTop : CGPoint! private var rightBottom : CGPoint! private var view1 : UIView! private var view2 : UIView! ///////////////////////////// /// Initialize init(view1 : UIView, view2 : UIView){ super.init(frame: CGRectZero); self.view1 = view1; self.view2 = view2; self.backgroundColor = UIColor.clearColor(); self.layer.zPosition = -2 self.update(); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } ///////////////////////////// /// setter ////// func setStrokeColor(color : UIColor){ self.strokeColor = color; } func setStrokeWidth(width : CGFloat){ self.strokeWidth = width; } func setZPosition(position : CGFloat){ self.layer.zPosition = position; } ///////////////// /// view update func update(){ let fP = view1.frame.origin; let tP = view2.frame.origin; self.leftTop = CGPointMake( small(fP.x, v2: tP.x), small(fP.y, v2: tP.y) ); self.rightBottom = CGPointMake( big(fP.x + view1.bounds.width, v2: tP.x + view2.bounds.width), big(fP.y + view1.bounds.height, v2: tP.y + view2.bounds.height) ); self.frame = CGRectMake(leftTop.x, leftTop.y, rightBottom.x - leftTop.x, rightBottom.y - leftTop.y); self.setNeedsDisplay(); } ///////////////// override func drawRect(rect: CGRect) { let firstCenter = CGPointMake(center(view1.frame).x - self.frame.origin.x, center(view1.frame).y - self.frame.origin.y); let secondCenter = CGPointMake(center(view2.frame).x - self.frame.origin.x, center(view2.frame).y - self.frame.origin.y); self.strokeColor.setStroke() // draw line let line = UIBezierPath(); line.setLineDash(dashPattern, count: dashPattern.count, phase: 0); line.moveToPoint(firstCenter); line.addLineToPoint(secondCenter); line.lineWidth = strokeWidth; line.lineCapStyle = CGLineCap.Round; line.stroke(); } //// Calc method private func center(rect : CGRect)->CGPoint { return CGPointMake(rect.origin.x + (rect.width / 2), rect.origin.y + (rect.height / 2)); } private func big(v1 : CGFloat, v2 : CGFloat)->CGFloat { return v1 >= v2 ? v1 : v2; } private func small(v1 : CGFloat, v2 : CGFloat)->CGFloat { return v1 >= v2 ? v2 : v1; } ////////////////// }
mit
3f43ad607cee9d5a1f39b8e5d273527b
27.432432
129
0.544216
4.124183
false
false
false
false
PurpleSweetPotatoes/customControl
SwiftKit/UI/BQPhotoView.swift
1
6527
// // BQPhotoView.swift // swift-test // // Created by baiqiang on 2017/6/16. // Copyright © 2017年 baiqiang. All rights reserved. // import UIKit class BQPhotoView: UIView { //MARK: - ***** Ivars ***** private(set) lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() private var singleTapAction: ((UITapGestureRecognizer) -> ())? fileprivate var scrollView: UIScrollView! private var backView: UIView! fileprivate var origiFrame: CGRect! class func show(imgView: UIImageView) { guard let image = imgView.image, let supView = imgView.superview else{ return } let showView = BQPhotoView(frame: UIScreen.main.bounds) showView.imageView.image = image showView.origiFrame = supView.convert(imgView.frame, to: UIApplication.shared.keyWindow?.rootViewController?.view) showView.tapAction { (tap) in showView.removeSelf() } UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(showView) showView.startAnimation() } class func show(img:UIImage) { let showView = BQPhotoView(frame: UIScreen.main.bounds) showView.imageView.image = img let imgSize = img.size let height = imgSize.height * showView.width / imgSize.width let frame = CGRect(x: 0, y: (showView.height - height) * 0.5, width: showView.width, height: height) showView.imageView.frame = frame UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(showView) } //MARK: - ***** initialize Method ***** private override init(frame: CGRect) { super.init(frame: frame) self.initUI() self.initGesture() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - ***** public Method ***** func tapAction(handle:@escaping (UITapGestureRecognizer) -> ()) { self.singleTapAction = handle } //MARK: - ***** private Method ***** private func initGesture() { let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(ges:))) singleTap.numberOfTapsRequired = 1 singleTap.numberOfTouchesRequired = 1 let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(ges:))) doubleTap.numberOfTapsRequired = 2 doubleTap.numberOfTouchesRequired = 1 // 允许优先执行doubleTap, 在doubleTap执行失败的时候执行singleTap, 如果没有设置这个, 那么将只会执行singleTap 不会执行doubleTap singleTap.require(toFail: doubleTap) self.addGestureRecognizer(singleTap) self.addGestureRecognizer(doubleTap) } private func initUI() { self.backView = UIView(frame: self.bounds) self.backView.backgroundColor = UIColor.black self.addSubview(self.backView) self.addScrollView() } private func startAnimation() { self.imageView.frame = self.origiFrame self.backView.alpha = 0 let imgSize = self.imageView.image!.size let height = imgSize.height * self.width / imgSize.width let frame = CGRect(x: 0, y: (self.height - height) * 0.5, width: self.width, height: height) UIView.animate(withDuration: 0.25, animations: { self.imageView.frame = frame self.backView.alpha = 1 }) } private func removeSelf() { UIView.animate(withDuration: 0.25, animations: { self.backView.alpha = 0 self.imageView.frame = self.origiFrame! }) { (finish) in self.removeFromSuperview() } } //MARK: - ***** LoadData Method ***** //MARK: - ***** respond event Method ***** // 单击手势, 给外界处理 @objc private func handleSingleTap(ges: UITapGestureRecognizer) { // 首先缩放到最小倍数, 以便于执行退出动画时frame可以同步改变 if scrollView.zoomScale != scrollView.minimumZoomScale { scrollView.setZoomScale(scrollView.minimumZoomScale, animated: false) } if let block = self.singleTapAction { block(ges) }else { self.removeFromSuperview() } } @objc private func handleDoubleTap(ges: UITapGestureRecognizer) { if self.imageView.image == nil { return } if scrollView.zoomScale <= scrollView.minimumZoomScale { let location = ges.location(in: imageView) let width = imageView.width/scrollView.maximumZoomScale let height = imageView.height/scrollView.maximumZoomScale let rect = CGRect(x: location.x - width * 0.5, y: location.y - height * 0.5, width: width, height: height) scrollView.zoom(to: rect, animated: true) print(scrollView.contentOffset) }else { scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true) } } //MARK: - ***** create Method ***** private func addScrollView() { let scrollView = UIScrollView(frame:self.bounds) scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.clipsToBounds = true scrollView.maximumZoomScale = 2.0 scrollView.minimumZoomScale = 1.0 scrollView.delegate = self self.imageView.frame = scrollView.bounds scrollView.addSubview(self.imageView) self.addSubview(scrollView) self.scrollView = scrollView } } //MARK:- ***** scrollviewDelegate ***** extension BQPhotoView : UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { // 居中显示图片 setImageViewToTheCenter() } // 居中显示图片 func setImageViewToTheCenter() { let offsetX = (scrollView.width > scrollView.contentSize.width) ? (scrollView.width - scrollView.contentSize.width)*0.5 : 0.0 let offsetY = (scrollView.height > scrollView.contentSize.height) ? (scrollView.height - scrollView.contentSize.height)*0.5 : 0.0 imageView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY) } }
apache-2.0
20b29be1401fa9db97ff992b9515e6e0
38.515528
137
0.64005
4.684831
false
false
false
false
Guzlan/Paths
MainViewController.swift
1
4669
// // MainViewController.swift // Paths // // Created by Amro Gazlan on 2016-06-30. // Copyright © 2016 Amro Gazlan. All rights reserved. // import Cocoa //import EonilFileSystemEvents class MainViewController: NSViewController, NSOutlineViewDelegate, NSTableViewDelegate { @IBOutlet weak var quiteButton: NSButton! @IBOutlet weak var refreshButton: NSButton! @IBOutlet weak var table: NSOutlineView! // the table that displays the file system heirarchy @IBOutlet weak var textField: NSTextField! // the textfield that displays the path of a file item @IBOutlet weak var dateTexField: NSTextField! // text field that displays the date of a file item @IBOutlet weak var typeTextField: NSTextField! // text field that displays the type of a file item let source = DataSource() // an instance of DataSource class let board = NSPasteboard.generalPasteboard() // the pasteboard that copies the path of file item to clipboard let dateFormatter = NSDateFormatter() // used to formate displayed date of a file item // function that copies the path to clipboard when the copy button is clicked @IBAction func clipboardCopy(sender: NSButton) { board.clearContents() // clear previous items on clipboard board.setString(textField.stringValue, forType: NSPasteboardTypeString) // copies the text displayed in textField to clipboard } @IBAction func refresh(sender: NSButton) { iterativeExpansion() } // terminates the application @IBAction func quiteButton(sender: NSButton) { NSApplication.sharedApplication().terminate(sender) } override func viewDidLoad() { super.viewDidLoad() // sitting the background color of the table self.view.wantsLayer = true self.view.layer?.backgroundColor = NSColor(calibratedRed: 0.949, green: 0.949, blue: 0.949, alpha: 1.00).CGColor self.table.backgroundColor = NSColor(calibratedRed: 0.949, green: 0.949, blue: 0.949, alpha: 1.00) // giving empty string to the path textField self.textField.stringValue = "" // setting shape of the refresh and quite button self.refreshButton.bezelStyle = NSBezelStyle.SmallSquareBezelStyle self.quiteButton.bezelStyle = NSBezelStyle.SmallSquareBezelStyle table.setDataSource(source) // setting the data source for the table table.setDelegate(self) // setting the OutlineViewDelegate as myself table.indentationPerLevel = CGFloat(20.0) // setting the indentaton distance table.setDraggingSourceOperationMask(NSDragOperation.Copy, forLocal: false) // allow dragging and copying items from the table table.allowsMultipleSelection = true // allows selecting multiple file items for drag and drop operation // formating the way the date is displayed self.dateFormatter.dateStyle = .MediumStyle self.dateFormatter.timeStyle = .NoStyle self.dateFormatter.locale = NSLocale(localeIdentifier: "en_US") } func iterativeExpansion()->(){ // goes through displayed rows in the table and // records the indixies of rows that are expanded var indexies = [Int]() for index in 0..<(self.table.numberOfRows) { if table.isItemExpanded(table.itemAtRow(index)){ indexies.append(index) } } self.table.reloadData() // reloads the data of the table var newIndex = 0 for index in indexies{ // because reloadData closes all previously expanded items // we will need to re expand them. self.table.expandItem(self.table?.itemAtRow(index)) // record the last expanded item newIndex = index } // scroll to the last expanded item self.table.scrollRowToVisible(newIndex) } // setting the textField string to the path of a selected file item func outlineView(outlineView: NSOutlineView, shouldSelectItem item: AnyObject) -> Bool { let filetItem = item as? FileSystemItem self.textField.stringValue = (filetItem?.getFullPath())! self.dateTexField.stringValue = dateFormatter.stringFromDate((filetItem?.getDate())!) if let fileItemExtension = NSURL(fileURLWithPath: (filetItem?.getFullPath())!).pathExtension where !fileItemExtension.isEmpty{ self.typeTextField.stringValue = fileItemExtension }else { self.typeTextField.stringValue = "Folder/No extension" } return true } }
mit
cb25e7339a2ede67a187ba7c0582fbba
43.037736
135
0.678021
4.981857
false
false
false
false
rogeruiz/MacPin
modules/MacPin/OSX/EffectViewController.swift
2
1039
import AppKit class EffectViewController: NSViewController { lazy var effectView: NSVisualEffectView = { var view = NSVisualEffectView() view.blendingMode = .BehindWindow view.material = .AppearanceBased //.Dark .Light .Titlebar view.state = NSVisualEffectState.Active // set it to always be blurry regardless of window state view.blendingMode = .BehindWindow view.frame = NSMakeRect(0, 0, 600, 800) // default size return view }() required init?(coder: NSCoder) { super.init(coder: coder) } // conform to NSCoding override init!(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nil, bundle:nil) } // calls loadView() override func loadView() { view = effectView } // NIBless convenience init() { self.init(nibName: nil, bundle: nil) } override func viewDidLoad() { view.autoresizesSubviews = true view.autoresizingMask = .ViewWidthSizable | .ViewHeightSizable //shouldn't matter if this is the contentView //view.translatesAutoresizingMaskIntoConstraints = true } }
gpl-3.0
f5b7e208310583b704ece36c5032035e
42.291667
141
0.746872
4.172691
false
false
false
false
wess/Appendix
Sources/shared/NSNumberFormatter+Appendix.swift
1
1453
// // NumberFormatter.swift // Appendix // // Created by Wesley Cope on 7/16/15. // Copyright © 2015 Wess Cope. All rights reserved. // import Foundation public enum AppendixNumberFormatterType { case Currency case Percent case None } public extension NumberFormatter { public class func currencyFormatter() -> NumberFormatter { let formatter = NumberFormatter() formatter.locale = NSLocale.current return formatter } public class func currencyFormatter(forLocal locale: Locale) -> NumberFormatter { let formatter = NumberFormatter() formatter.locale = locale return formatter } public class func percentFormatter() -> NumberFormatter { let formatter = NumberFormatter.percentFormatter(forLocal: Locale.current) return formatter } public class func percentFormatter(forLocal locale: Locale) -> NumberFormatter { let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = .percent return formatter } public convenience init(locale:Locale?, type:AppendixNumberFormatterType = .None) { self.init() self.locale = locale ?? Locale.current switch type { case .Currency: numberStyle = .currency break case .Percent: numberStyle = .percent break default: numberStyle = .none break } } }
mit
10cb62d90fe380810967cc878f29fd2a
20.671642
85
0.652893
5.024221
false
false
false
false
TheBudgeteers/CartTrackr
CartTrackr/CartTrackr/Extensions.swift
1
2112
// // UIExtensions.swift // CartTrackr // // Created by Christina Lee on 4/10/17. // Copyright © 2017 Christina Lee. All rights reserved. // import UIKit extension UIResponder { static var identifier : String { return String(describing: self) } } //Extension to allow using hex value color selection in code extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } //Converts hex value to Int and applies it to RGB values in correct order convenience init(rgb: Int) { self.init( red: (rgb >> 16) & 0xFF, green: (rgb >> 8) & 0xFF, blue: rgb & 0xFF ) } } extension String { // formatting text for currency textField func currencyInputFormatting() -> String { var number: NSNumber! let formatter = NumberFormatter() formatter.numberStyle = .currencyAccounting formatter.currencySymbol = "$" formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 var amountWithPrefix = self // remove from String: "$", ".", "," let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive) amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "") let double = (amountWithPrefix as NSString).doubleValue number = NSNumber(value: (double / 100)) // if first number is 0 or all numbers were deleted guard number != 0 as NSNumber else { return "" } return formatter.string(from: number)! } }
mit
b963385e73dbf62dc3b789422ccae076
30.044118
202
0.603979
4.520343
false
false
false
false
xivol/MCS-V3-Mobile
examples/extras/photos/advImProcessing/advImProcessing/Image Processing/CarnivalMirror.swift
1
4999
// // CarnivalMirror.swift // Filterpedia // // Created by Simon Gladman on 09/02/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import CoreImage class CarnivalMirror: CIFilter { var inputImage : CIImage? var inputHorizontalWavelength: CGFloat = 10 var inputHorizontalAmount: CGFloat = 20 var inputVerticalWavelength: CGFloat = 10 var inputVerticalAmount: CGFloat = 20 override func setDefaults() { inputHorizontalWavelength = 10 inputHorizontalAmount = 20 inputVerticalWavelength = 10 inputVerticalAmount = 20 } override var attributes: [String : Any] { return [ kCIAttributeFilterName: "CarnivalMirror", kCIAttributeFilterDisplayName: "Carnival Mirror", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputHorizontalWavelength": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Horizontal Wavelength", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputHorizontalAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Horizontal Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputVerticalWavelength": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Vertical Wavelength", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputVerticalAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Vertical Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar] ] } let carnivalMirrorKernel = CIWarpKernel(source: "kernel vec2 carnivalMirror(float xWavelength, float xAmount, float yWavelength, float yAmount)" + "{" + " float y = destCoord().y + sin(destCoord().y / yWavelength) * yAmount; " + " float x = destCoord().x + sin(destCoord().x / xWavelength) * xAmount; " + " return vec2(x, y); " + "}" ) override var outputImage : CIImage! { guard let inputImage = inputImage, let kernel = carnivalMirrorKernel else { return nil } let arguments = [ inputHorizontalWavelength, inputHorizontalAmount, inputVerticalWavelength, inputVerticalAmount] let extent = inputImage.extent return kernel.apply(extent: extent, roiCallback: { (index, rect) in return rect }, image: inputImage, arguments: arguments) } }
mit
dd70a28e568d5f1f6965e02bf0620be9
40.65
106
0.520608
6.399488
false
false
false
false
proversity-org/edx-app-ios
Source/CourseDashboardLoadStateViewController.swift
1
1279
// // CourseDashboardLoadStateViewController.swift // edX // // Created by Salman on 09/11/2017. // Copyright © 2017 edX. All rights reserved. // import UIKit class CourseDashboardLoadStateViewController: UIViewController { typealias Environment = OEXStylesProvider public let loadController = LoadStateViewController() private let contentView = UIView() private let environment: Environment init(environment: Environment) { self.environment = environment super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(contentView) contentView.snp.makeConstraints { make in make.edges.equalTo(safeEdges) } view.backgroundColor = environment.styles.standardBackgroundColor() loadController.setupInController(controller: self, contentView: contentView) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
d9682fd5af28523ead0338978e342e2a
27.4
84
0.672144
5.392405
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/ProjectActivities/Views/Cells/ProjectActivityLaunchCell.swift
1
1689
import KsApi import Library import Prelude import Prelude_UIKit import UIKit internal final class ProjectActivityLaunchCell: UITableViewCell, ValueCell { fileprivate let viewModel: ProjectActivityLaunchCellViewModelType = ProjectActivityLaunchCellViewModel() @IBOutlet fileprivate var cardView: UIView! @IBOutlet fileprivate var titleLabel: UILabel! internal func configureWith(value activityAndProject: (Activity, Project)) { self.viewModel.inputs.configureWith( activity: activityAndProject.0, project: activityAndProject.1 ) } internal override func bindViewModel() { super.bindViewModel() self.viewModel.outputs.title.observeForUI() .observeValues { [weak titleLabel] title in guard let titleLabel = titleLabel else { return } titleLabel.attributedText = title.simpleHtmlAttributedString( font: .ksr_body(), bold: UIFont.ksr_body().bolded, italic: nil ) _ = titleLabel |> projectActivityStateChangeLabelStyle |> UILabel.lens.textColor .~ .ksr_support_700 } } internal override func bindStyles() { super.bindStyles() _ = self |> baseTableViewCellStyle() |> ProjectActivityLaunchCell.lens.contentView.layoutMargins %~~ { layoutMargins, cell in cell.traitCollection.isRegularRegular ? projectActivityRegularRegularLayoutMargins : layoutMargins } |> UITableViewCell.lens.accessibilityHint %~ { _ in Strings.Opens_project() } _ = self.cardView |> cardStyle() |> dropShadowStyleMedium() |> UIView.lens.layer.borderColor .~ UIColor.ksr_support_700.cgColor } }
apache-2.0
5ff7bc816c063b9f26d91879a1791d17
29.160714
106
0.694494
5.165138
false
false
false
false
jpedrosa/sua
examples/benchmarks/swift_richards/Sources/main.swift
1
15622
// Copyright 2006-2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. 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 // OWNER 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. // Ported by the Dart team to Dart. // Translated to Swift by Joao Pedrosa. // This is a Dart implementation of the Richards benchmark from: // // http://www.cl.cam.ac.uk/~mr10/Bench.html // // The benchmark was originally implemented in BCPL by // Martin Richards. import Glibc import Sua /** * Richards imulates the task dispatcher of an operating system. **/ class Richards { func run() throws { let scheduler = Scheduler() scheduler.addIdleTask(id: Richards.ID_IDLE, priority: 0, queue: nil, count: Richards.COUNT) var queue = Packet(link: nil, id: Richards.ID_WORKER, kind: Richards.KIND_WORK) queue = Packet(link: queue, id: Richards.ID_WORKER, kind: Richards.KIND_WORK) scheduler.addWorkerTask(id: Richards.ID_WORKER, priority: 1000, queue: queue) queue = Packet(link: nil, id: Richards.ID_DEVICE_A, kind: Richards.KIND_DEVICE) queue = Packet(link: queue, id: Richards.ID_DEVICE_A, kind: Richards.KIND_DEVICE) queue = Packet(link: queue, id: Richards.ID_DEVICE_A, kind: Richards.KIND_DEVICE) scheduler.addHandlerTask(id: Richards.ID_HANDLER_A, priority: 2000, queue: queue) queue = Packet(link: nil, id: Richards.ID_DEVICE_B, kind: Richards.KIND_DEVICE) queue = Packet(link: queue, id: Richards.ID_DEVICE_B, kind: Richards.KIND_DEVICE) queue = Packet(link: queue, id: Richards.ID_DEVICE_B, kind: Richards.KIND_DEVICE) scheduler.addHandlerTask(id: Richards.ID_HANDLER_B, priority: 3000, queue: queue) scheduler.addDeviceTask(id: Richards.ID_DEVICE_A, priority: 4000, queue: nil) scheduler.addDeviceTask(id: Richards.ID_DEVICE_B, priority: 5000, queue: nil) scheduler.schedule() if scheduler.queueCount != Richards.EXPECTED_QUEUE_COUNT || scheduler.holdCount != Richards.EXPECTED_HOLD_COUNT { print("Error during execution: queueCount = \(scheduler.queueCount)" + ", holdCount = \(scheduler.holdCount).") } if Richards.EXPECTED_QUEUE_COUNT != scheduler.queueCount { throw SchedulerError.WrongQueueCount } if Richards.EXPECTED_HOLD_COUNT != scheduler.holdCount { throw SchedulerError.WrongHoldCount } } static let DATA_SIZE = 4 static let COUNT = 1000 /** * These two constants specify how many times a packet is queued and * how many times a task is put on hold in a correct run of richards. * They don't have any meaning a such but are characteristic of a * correct run so if the actual queue or hold count is different from * the expected there must be a bug in the implementation. **/ static let EXPECTED_QUEUE_COUNT = 2322 static let EXPECTED_HOLD_COUNT = 928 static let ID_IDLE = 0 static let ID_WORKER = 1 static let ID_HANDLER_A = 2 static let ID_HANDLER_B = 3 static let ID_DEVICE_A = 4 static let ID_DEVICE_B = 5 static let NUMBER_OF_IDS = 6 static let KIND_DEVICE = 0 static let KIND_WORK = 1 } /** * A scheduler can be used to schedule a set of tasks based on their relative * priorities. Scheduling is done by maintaining a list of task control blocks * which holds tasks and the data queue they are processing. */ class Scheduler { var queueCount = 0 var holdCount = 0 var currentTcb: TaskControlBlock? var currentId = 0 var list: TaskControlBlock? var blocks = [TaskControlBlock?](repeating: nil, count: Richards.NUMBER_OF_IDS) /// Add an idle task to this scheduler. func addIdleTask(id: Int, priority: Int, queue: Packet?, count: Int) { addRunningTask(id: id, priority: priority, queue: queue, task: IdleTask(scheduler: self, v1: 1, count: count)) } /// Add a work task to this scheduler. func addWorkerTask(id: Int, priority: Int, queue: Packet) { addTask(id: id, priority: priority, queue: queue, task: WorkerTask(scheduler: self, v1: Richards.ID_HANDLER_A, v2: 0)) } /// Add a handler task to this scheduler. func addHandlerTask(id: Int, priority: Int, queue: Packet) { addTask(id: id, priority: priority, queue: queue, task: HandlerTask(scheduler: self)) } /// Add a handler task to this scheduler. func addDeviceTask(id: Int, priority: Int, queue: Packet?) { addTask(id: id, priority: priority, queue: queue, task: DeviceTask(scheduler: self)) } /// Add the specified task and mark it as running. func addRunningTask(id: Int, priority: Int, queue: Packet?, task: Task) { addTask(id: id, priority: priority, queue: queue, task: task) currentTcb!.setRunning() } /// Add the specified task to this scheduler. func addTask(id: Int, priority: Int, queue: Packet?, task: Task) { currentTcb = TaskControlBlock(link: list, id: id, priority: priority, queue: queue, task: task) list = currentTcb blocks[id] = currentTcb } /// Execute the tasks managed by this scheduler. func schedule() { currentTcb = list while currentTcb != nil { if currentTcb!.isHeldOrSuspended() { currentTcb = currentTcb!.link } else { currentId = currentTcb!.id currentTcb = currentTcb!.run() } } } /// Release a task that is currently blocked and return the next block to run. func release(id: Int) -> TaskControlBlock? { guard let tcb = blocks[id] else { return nil } tcb.markAsNotHeld() if tcb.priority > currentTcb!.priority { return tcb } return currentTcb } /** * Block the currently executing task and return the next task control block * to run. The blocked task will not be made runnable until it is explicitly * released, even if new work is added to it. */ func holdCurrent() -> TaskControlBlock? { holdCount += 1 currentTcb!.markAsHeld() return currentTcb!.link } /** * Suspend the currently executing task and return the next task * control block to run. * If new work is added to the suspended task it will be made runnable. */ func suspendCurrent() -> TaskControlBlock { currentTcb!.markAsSuspended() return currentTcb! } /** * Add the specified packet to the end of the worklist used by the task * associated with the packet and make the task runnable if it is currently * suspended. */ func queue(packet: Packet) -> TaskControlBlock? { guard let t = blocks[packet.id] else { return nil } queueCount += 1 packet.link = nil packet.id = currentId return t.checkPriorityAdd(task: currentTcb!, packet: packet) } } /** * A task control block manages a task and the queue of work packages associated * with it. */ class TaskControlBlock: CustomStringConvertible { var link: TaskControlBlock? var id = 0 // The id of this block. var priority = 0 // The priority of this block. var queue: Packet? // The queue of packages to be processed by the task. var task: Task? var state = 0 init(link: TaskControlBlock?, id: Int, priority: Int, queue: Packet?, task: Task) { self.link = link self.id = id self.priority = priority self.queue = queue self.task = task state = queue == nil ? TaskControlBlock.STATE_SUSPENDED : TaskControlBlock.STATE_SUSPENDED_RUNNABLE } /// The task is running and is currently scheduled. static let STATE_RUNNING = 0 /// The task has packets left to process. static let STATE_RUNNABLE = 1 /** * The task is not currently running. The task is not blocked as such and may * be started by the scheduler. */ static let STATE_SUSPENDED = 2 /// The task is blocked and cannot be run until it is explicitly released. static let STATE_HELD = 4 static let STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE static let STATE_NOT_HELD = ~STATE_HELD func setRunning() { state = TaskControlBlock.STATE_RUNNING } func markAsNotHeld() { state = state & TaskControlBlock.STATE_NOT_HELD } func markAsHeld() { state = state | TaskControlBlock.STATE_HELD } func isHeldOrSuspended() -> Bool { return (state & TaskControlBlock.STATE_HELD) != 0 || (state == TaskControlBlock.STATE_SUSPENDED) } func markAsSuspended() { state = state | TaskControlBlock.STATE_SUSPENDED } func markAsRunnable() { state = state | TaskControlBlock.STATE_RUNNABLE } /// Runs this task, if it is ready to be run, and returns the next task to run. func run() -> TaskControlBlock? { var packet: Packet? if state == TaskControlBlock.STATE_SUSPENDED_RUNNABLE { packet = queue queue = packet!.link state = queue == nil ? TaskControlBlock.STATE_RUNNING : TaskControlBlock.STATE_RUNNABLE } return task!.run(packet: packet) } /** * Adds a packet to the worklist of this block's task, marks this as * runnable if necessary, and returns the next runnable object to run * (the one with the highest priority). */ func checkPriorityAdd(task: TaskControlBlock, packet: Packet) -> TaskControlBlock { if queue == nil { queue = packet markAsRunnable() if priority > task.priority { return self } } else { queue = packet.addTo(queue: queue) } return task } var description: String { return "tcb { \(task)@\(state) }" } } /** * Abstract task that manipulates work packets. */ class Task { let scheduler: Scheduler // The scheduler that manages this task. init(scheduler: Scheduler) { self.scheduler = scheduler } // Override me. func run(packet: Packet?) -> TaskControlBlock? { return nil } } /** * An idle task doesn't do any work itself but cycles control between the two * device tasks. */ class IdleTask: Task, CustomStringConvertible { var v1 = 0 // A seed value that controls how the device tasks are scheduled. var count = 0 // The number of times this task should be scheduled. init(scheduler: Scheduler, v1: Int, count: Int) { self.v1 = v1 self.count = count super.init(scheduler: scheduler) } override func run(packet: Packet?) -> TaskControlBlock? { count -= 1 if count == 0 { return scheduler.holdCurrent() } if (v1 & 1) == 0 { v1 = v1 >> 1 return scheduler.release(id: Richards.ID_DEVICE_A) } v1 = (v1 >> 1) ^ 0xD008 return scheduler.release(id: Richards.ID_DEVICE_B) } var description: String { return "IdleTask" } } /** * A task that suspends itself after each time it has been run to simulate * waiting for data from an external device. */ class DeviceTask: Task, CustomStringConvertible { var v1: Packet? override func run(packet: Packet?) -> TaskControlBlock? { if packet == nil { guard let v = v1 else { return scheduler.suspendCurrent() } v1 = nil return scheduler.queue(packet: v) } v1 = packet return scheduler.holdCurrent() } var description: String { return "DeviceTask" } } /** * A task that manipulates work packets. */ class WorkerTask: Task, CustomStringConvertible { var v1 = 0 // A seed used to specify how work packets are manipulated. var v2 = 0 // Another seed used to specify how work packets are manipulated. init(scheduler: Scheduler, v1: Int, v2: Int) { self.v1 = v1 self.v2 = v2 super.init(scheduler: scheduler) } override func run(packet: Packet?) -> TaskControlBlock? { guard let packet = packet else { return scheduler.suspendCurrent() } if v1 == Richards.ID_HANDLER_A { v1 = Richards.ID_HANDLER_B } else { v1 = Richards.ID_HANDLER_A } packet.id = v1 packet.a1 = 0 for i in 0..<Richards.DATA_SIZE { v2 += 1 if v2 > 26 { v2 = 1 } packet.a2[i] = v2 } return scheduler.queue(packet: packet) } var description: String { return "WorkerTask" } } /** * A task that manipulates work packets and then suspends itself. */ class HandlerTask: Task, CustomStringConvertible { var v1: Packet? var v2: Packet? override func run(packet: Packet?) -> TaskControlBlock? { if let packet = packet { if packet.kind == Richards.KIND_WORK { v1 = packet.addTo(queue: v1) } else { v2 = packet.addTo(queue: v2) } } if let v1 = v1 { let count = v1.a1 if count < Richards.DATA_SIZE { if let v2 = v2 { let v = v2 self.v2 = v2.link v.a1 = v1.a2[count] v1.a1 = count + 1 return scheduler.queue(packet: v) } } else { let v = v1 self.v1 = v1.link return scheduler.queue(packet: v) } } return scheduler.suspendCurrent() } var description: String { return "HandlerTask" } } /** * A simple package of data that is manipulated by the tasks. The exact layout * of the payload data carried by a packet is not importaint, and neither is the * nature of the work performed on packets by the tasks. * Besides carrying data, packets form linked lists and are hence used both as * data and worklists. */ class Packet: CustomStringConvertible { var link: Packet? // The tail of the linked list of packets. var id = 0 // An ID for this packet. var kind = 0 // The type of this packet. var a1 = 0 var a2 = [Int](repeating: 0, count: Richards.DATA_SIZE) init(link: Packet?, id: Int, kind: Int) { self.link = link self.id = id self.kind = kind } /// Add this packet to the end of a worklist, and return the worklist. func addTo(queue: Packet?) -> Packet { link = nil guard let q = queue else { return self } var next = q var peek = next.link while peek != nil { next = peek! peek = next.link } next.link = self return q } var description: String { return "Packet" } } enum SchedulerError: ErrorProtocol { case WrongQueueCount case WrongHoldCount } let sw = Stopwatch() sw.start() let o = Richards() try o.run() print("Elapsed: \(sw.millis)")
apache-2.0
b345c7ee86decc008816933cdb457ff0
27.92963
81
0.664128
3.74359
false
false
false
false
zom/Zom-iOS
Zom/Zom/Classes/Views/HighlightableButton.swift
1
1432
// // MatchButton.swift // Zom // // Created by Benjamin Erhart on 26.02.18. // import UIKit /** UIButton which allows setting of background and border colors for normal and highlighted states. This can also be done using the Interface Builder via it's "User Defined Runtime Attributes" list. */ @objc class HighlightableButton: UIButton { @IBInspectable var normalBackgroundColor = UIColor.clear { didSet { backgroundColor = isHighlighted ? highlightedBackgroundColor : normalBackgroundColor } } @IBInspectable var highlightedBackgroundColor = UIColor.clear { didSet { backgroundColor = isHighlighted ? highlightedBackgroundColor : normalBackgroundColor } } @IBInspectable var normalBorderColor = UIColor.clear { didSet { layer.borderColor = isHighlighted ? highlightedBorderColor.cgColor : normalBorderColor.cgColor } } @IBInspectable var highlightedBorderColor = UIColor.clear { didSet { layer.borderColor = isHighlighted ? highlightedBorderColor.cgColor : normalBorderColor.cgColor } } override open var isHighlighted: Bool { didSet { backgroundColor = isHighlighted ? highlightedBackgroundColor : normalBackgroundColor layer.borderColor = isHighlighted ? highlightedBorderColor.cgColor : normalBorderColor.cgColor } } }
mpl-2.0
365b05cbf5ad92359bbef0bd85ba2f22
28.833333
106
0.690642
5.571984
false
false
false
false
codinn/SSHKitCore
SSHKitCoreTests/EchoServer.swift
1
3573
// // EchoServer.swift // SwiftSockets // // Created by Helge Hess on 6/13/14. // Copyright (c) 2014 Always Right Institute. All rights reserved. // import SwiftSockets import Dispatch #if os(Linux) // for sockaddr_in import Glibc #else import Darwin #endif class EchoServer { let port : Int var listenSocket : PassiveSocketIPv4? let lockQueue = dispatch_queue_create("com.ari.socklock", nil) var openSockets = [FileDescriptor:ActiveSocket<sockaddr_in>](minimumCapacity: 8) var appLog : ((String) -> Void)? init(port: Int) { self.port = port } func log(s: String) { if let lcb = appLog { lcb(s) } else { print(s) } } func start() { listenSocket = PassiveSocketIPv4(address: sockaddr_in(port: port)) if listenSocket == nil || !listenSocket! { // neat, eh? ;-) log("ERROR: could not create socket ...") return } log("Listen socket \(listenSocket)") log(welcomeText) let queue = dispatch_get_global_queue(0, 0) // Note: capturing self here listenSocket!.listen(queue:queue, backlog: 5) { newSock in self.log("got new socket: \(newSock) nio=\(newSock.isNonBlocking)") newSock.isNonBlocking = true dispatch_async(self.lockQueue) { // Note: we need to keep the socket around!! self.openSockets[newSock.fd] = newSock } newSock.onRead { self.handleIncomingData($0, expectedCount: $1) } .onClose { ( fd: FileDescriptor ) -> Void in // we need to consume the return value to give peace to the closure dispatch_async(self.lockQueue) { [unowned self] in #if swift(>=3.0) _ = self.openSockets.removeValue(forKey: fd) #else _ = self.openSockets.removeValueForKey(fd) #endif } } } log("Started running listen socket \(listenSocket)") } func stop() { listenSocket?.close() listenSocket = nil } let welcomeText = "\r\n" + " /----------------------------------------------------\\\r\n" + " | Welcome to the Always Right Institute! |\r\n" + " | I am an echo server with a zlight twist. |\r\n" + " | Just type something and I'll shout it back at you. |\r\n" + " \\----------------------------------------------------/\r\n" + "\r\nTalk to me Dave!\r\n" + "> " func handleIncomingData<T>(socket: ActiveSocket<T>, expectedCount: Int) { // remove from openSockets if all has been read repeat { // FIXME: This currently continues to read garbage if I just close the // Terminal which hosts telnet. Even with sigpipe off. let (count, block, errno) = socket.read() if count < 0 && errno == EWOULDBLOCK { break } if count < 1 { log("EOF \(socket) (err=\(errno))") socket.close() return } socket.asyncWrite(buffer:block, length: count) } while (true) } }
lgpl-2.1
2a1eca1f480113d2651e3f6e6e55b888
30.069565
87
0.47691
4.46625
false
false
false
false
Jvaeyhcd/NavTabBarController
NavTabBarControllerDemo/NavTabBarControllerDemo/SlippedDemoViewController.swift
1
2451
// // SlippedDemoViewController.swift // NavTabBarControllerDemo // // Created by Jvaeyhcd on 21/04/2017. // Copyright © 2017 Jvaeyhcd. All rights reserved. // import UIKit class SlippedDemoViewController: SlippedViewController { override func viewDidLoad() { super.viewDidLoad() let vc1 = SlippedTableViewController() vc1.title = "全部" let vc2 = SlippedTableViewController() vc2.title = "新鲜" let vc3 = SlippedTableViewController() vc3.title = "热门" setTabBarFrame(tabBarFrame: CGRect(x: 0, y: 200, width: kScreenWidth, height: 50), contentViewFrame: CGRect(x: 0, y: 50 + 200, width: kScreenWidth, height: kScreenHeight - 50 - 200)) // self.tabBar?.setItemWidth(itemWidth: UIScreen.main.bounds.width / 5) // self.tabBar?.setAutoResizeItemWidth(auto: true) self.tabBar?.setItemWidth(itemWidth: kScreenWidth / 3) self.tabBar?.setFramePadding(top: 0, left: 0, bottom: 0, right: 0) self.tabBar?.setItemHorizontalPadding(itemHorizontalPadding: 50) self.tabBar?.setItemSelectedBgInsets(itemSelectedBgInsets: UIEdgeInsetsMake(48, 50, 0, 50)) self.tabBar?.showSelectedBgView(show: true) self.tabBar?.setItemTitleSelectedFont(itemTitleSelectedFont: UIFont.systemFont(ofSize: 14)) self.tabBar?.setItemTitleFont(itemTitleFont: UIFont.systemFont(ofSize: 14)) self.tabBar?.setItemTitleColor(itemTitleColor: UIColor.init(red: 0.012, green: 0.663, blue: 0.961, alpha: 1.00)) self.tabBar?.setItemTitleSelectedColor(itemTitleSelectedColor: UIColor.init(red: 0.012, green: 0.663, blue: 0.961, alpha: 1.00)) self.tabBar?.setItemSelectedBgImageViewColor(itemSelectedBgImageViewColor: UIColor.init(red: 0.012, green: 0.663, blue: 0.961, alpha: 1.00)) setViewControllers(viewControllers: [vc1, vc2, vc3]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
20bee57db55f3fdd5a395e69e629c5c5
41.034483
190
0.683347
4.118243
false
false
false
false
notohiro/NowCastMapView
NowCastMapView/BaseTimeModel.swift
1
2665
// // BaseTimeModel.swift // NowCastMapView // // Created by Hiroshi Noto on 9/15/15. // Copyright © 2015 Hiroshi Noto. All rights reserved. // import Foundation public protocol BaseTimeProvider { var fetchInterval: TimeInterval { get set } var current: BaseTime? { get } } public protocol BaseTimeModelDelegate: class { func baseTimeModel(_ model: BaseTimeModel, fetched baseTime: BaseTime?) } /** An `BaseTimeModel` object lets you fetch the `BaseTime`. */ open class BaseTimeModel: BaseTimeProvider { internal enum Constants { // swiftlint:disable:next force_unwrapping internal static let url = URL(string: "http://www.jma.go.jp/jp/highresorad/highresorad_tile/tile_basetime.xml")! internal static let fts = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60] } open weak var delegate: BaseTimeModelDelegate? private let session = URLSession(configuration: URLSessionConfiguration.default) private var fetching = false private var fetchTimer: Timer? /// immediately fetch + interval open var fetchInterval: TimeInterval = 0 { // 0 means will never check automatically didSet { objc_sync_enter(self) fetchTimer?.invalidate() if fetchInterval != 0 { let fetchTimer = Timer(timeInterval: fetchInterval, target: self, selector: #selector(BaseTimeModel.fetch), userInfo: nil, repeats: true) RunLoop.main.add(fetchTimer, forMode: RunLoop.Mode.common) self.fetchTimer = fetchTimer fetch() } objc_sync_exit(self) } } open internal(set) var current: BaseTime? { didSet { delegate?.baseTimeModel(self, fetched: current) } } public init() { } @objc open func fetch() { objc_sync_enter(self) if fetching { return } else { fetching = true } objc_sync_exit(self) let task = session.dataTask(with: Constants.url) { [unowned self] data, _, error in if error != nil { // do something? } else { let baseTime = data.flatMap { BaseTime(baseTimeData: $0) } if self.current == nil, let baseTime = baseTime { self.current = baseTime } else if let current = self.current, let baseTime = baseTime, current < baseTime { self.current = baseTime } } self.fetching = false } task.priority = URLSessionTask.highPriority task.resume() } }
mit
49df3f84c39da9a1cc1def36f403927e
27.645161
117
0.590465
4.182104
false
false
false
false
skedgo/tripkit-ios
Sources/TripKit/vendor/ASPolygonKit/MKPolygon+Union.swift
1
4500
// // MKPolygon+Union.swift // // Created by Adrian Schoenig on 18/2/17. // // #if canImport(MapKit) import MapKit #endif extension Polygon { static func union(_ polygons: [Polygon]) throws -> [Polygon] { let sorted = polygons.sorted { first, second in if first.minY < second.minY { return true } else if second.minY < first.minY { return false } else { return first.minX < second.minX } } return try sorted.reduce([]) { polygons, polygon in try union(polygons, with: polygon) } } static func union(_ polygons: [Polygon], with polygon: Polygon) throws -> [Polygon] { var grower = polygon.clockwise() var newArray: [Polygon] = [] for existing in polygons { if existing.contains(grower) { grower = existing continue } let clockwise = existing.clockwise() let intersections = grower.intersections(clockwise) if intersections.count > 0 { let merged = try grower.union(clockwise, with: intersections) if !merged { newArray.append(clockwise) } } else { newArray.append(clockwise) } } newArray.append(grower) return newArray } } #if canImport(MapKit) extension MKPolygon { class func union(_ polygons: [MKPolygon], completion: @escaping (Result<[MKPolygon], Error>) -> Void) { let queue = DispatchQueue(label: "MKPolygonUnionMerger", qos: .background) queue.async { let result = Result { try union(polygons) } DispatchQueue.main.async { completion(result) } } } class func union(_ polygons: [MKPolygon]) throws -> [MKPolygon] { let sorted = polygons.sorted(by: { first, second in return first.boundingMapRect.distanceFromOrigin < second.boundingMapRect.distanceFromOrigin }) return try sorted.reduce([]) { polygons, polygon in return try union(polygons, with: polygon) } } class func union(_ polygons: [MKPolygon], with polygon: MKPolygon) throws -> [MKPolygon] { var grower = Polygon(polygon) var newArray: [MKPolygon] = [] for existing in polygons { let existingStruct = Polygon(existing) if existingStruct.contains(grower) { grower = existingStruct continue } let intersections = grower.intersections(existingStruct) if intersections.count > 0 { let merged = try grower.union(existingStruct, with: intersections) if !merged { newArray.append(existing) } } else { newArray.append(existing) } } newArray.append(grower.polygon) return newArray } func contains(_ coordinate: CLLocationCoordinate2D) -> Bool { if (!boundingMapRect.contains(MKMapPoint(coordinate))) { return false } // It's in the bounding rect, but is it in the detailed shape? let polygon = Polygon(self) let point = Point(latitude: coordinate.latitude, longitude: coordinate.longitude) return polygon.contains(point, onLine: true) } } extension MKMapRect { var distanceFromOrigin: Double { return sqrt( origin.x * origin.x + origin.y * origin.y ) } } //MARK: - Compatibility extension Point { var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: lat, longitude: lng) } var annotation: MKPointAnnotation { let point = MKPointAnnotation() point.coordinate = self.coordinate return point } } extension Line { var polyline: MKPolyline { var points = [start.coordinate, end.coordinate] return MKPolyline(coordinates: &points, count: points.count) } } extension Polygon { /// Creates a new polygon from an `MKPolygon`, ignoring interior polygons init(_ polygon: MKPolygon) { let count = polygon.pointCount var coordinates = [CLLocationCoordinate2D](repeating: kCLLocationCoordinate2DInvalid, count: count) let range = NSRange(location: 0, length: count) polygon.getCoordinates(&coordinates, range: range) points = coordinates.map { coordinate in Point(latitude: coordinate.latitude, longitude: coordinate.longitude) } firstLink = Polygon.firstLink(for: points) } /// The polygon as an `MKPolygon`, ignoring interior polygons var polygon: MKPolygon { var coordinates = points.map { point in point.coordinate } return MKPolygon(coordinates: &coordinates, count: coordinates.count) } } #endif
apache-2.0
f0631ca1843c70a30e3cdede747323bd
25.627219
105
0.652667
4.26945
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Producer.swift
8
3033
// // Producer.swift // RxSwift // // Created by Krunoslav Zaher on 2/20/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // class Producer<Element>: Observable<Element> { override init() { super.init() } override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { if !CurrentThreadScheduler.isScheduleRequired { // The returned disposable needs to release all references once it was disposed. let disposer = SinkDisposer() let sinkAndSubscription = self.run(observer, cancel: disposer) disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) return disposer } else { return CurrentThreadScheduler.instance.schedule(()) { _ in let disposer = SinkDisposer() let sinkAndSubscription = self.run(observer, cancel: disposer) disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) return disposer } } } func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { rxAbstractMethod() } } private final class SinkDisposer: Cancelable { private enum DisposeState: Int32 { case disposed = 1 case sinkAndSubscriptionSet = 2 } private let state = AtomicInt(0) private var sink: Disposable? private var subscription: Disposable? var isDisposed: Bool { isFlagSet(self.state, DisposeState.disposed.rawValue) } func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { self.sink = sink self.subscription = subscription let previousState = fetchOr(self.state, DisposeState.sinkAndSubscriptionSet.rawValue) if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { rxFatalError("Sink and subscription were already set") } if (previousState & DisposeState.disposed.rawValue) != 0 { sink.dispose() subscription.dispose() self.sink = nil self.subscription = nil } } func dispose() { let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) if (previousState & DisposeState.disposed.rawValue) != 0 { return } if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { guard let sink = self.sink else { rxFatalError("Sink not set") } guard let subscription = self.subscription else { rxFatalError("Subscription not set") } sink.dispose() subscription.dispose() self.sink = nil self.subscription = nil } } }
mit
42596279c4dee0c5537372bbff578107
31.956522
162
0.628628
5.319298
false
false
false
false
sammeadley/TopStories
TopStories/AppDelegate.swift
1
2582
// // AppDelegate.swift // TopStories // // Created by Sam Meadley on 19/04/2016. // Copyright © 2016 Sam Meadley. All rights reserved. // import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var persistenceController: PersistenceController? var requestController: RequestController? // MARK: - UIApplicationDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { persistenceController = PersistenceController() if let managedObjectContext = persistenceController?.managedObjectContext { requestController = RequestController(managedObjectContext: managedObjectContext) } let splitViewController = self.window!.rootViewController as! UISplitViewController splitViewController.delegate = self let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem navigationController.topViewController!.navigationItem.leftItemsSupplementBackButton = true let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! StoriesViewController controller.managedObjectContext = persistenceController?.managedObjectContext; controller.requestController = requestController return true } func applicationWillTerminate(_ application: UIApplication) { // Saves changes in the application's managed object context before the application terminates. guard let managedObjectContext = self.persistenceController?.managedObjectContext else { return; } if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // TODO: Handle error } } } } extension AppDelegate: UISplitViewControllerDelegate { func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { return true } }
mit
9070d29ee57f0e5ed132ec2ada7af96d
38.106061
144
0.698954
7.353276
false
false
false
false
ryanspillsbury90/OmahaTutorial
ios/OmahaPokerTutorial/OmahaPokerTutorial/MenuTableViewController.swift
1
4389
// // MenuTableViewController.swift // // Created by Ryan Pillsbury on 6/2/15. // Copyright (c) 2015 koait. All rights reserved. // import UIKit class MenuTableViewController: UITableViewController { var selectedMenuItem : Int = 0 var menuData = [ "Omaha Tutorial", "Travel Reno ", "All Promotions" ]; override func viewDidLoad() { super.viewDidLoad() // Customize apperance of table view tableView.contentInset = UIEdgeInsetsMake(64.0, 0, 0, 0) // tableView.separatorStyle = .None tableView.backgroundColor = UIColor(red: 33.0 / 256.0, green: 30.0 / 256.0, blue: 30.0 / 256.0, alpha: 0.7) tableView.scrollsToTop = false // Preserve selection between presentations self.clearsSelectionOnViewWillAppear = false tableView.selectRowAtIndexPath(NSIndexPath(forRow: selectedMenuItem, inSection: 0), animated: false, scrollPosition: .Middle) } 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 the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return menuData.count; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("CELL"); if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CELL") cell!.backgroundColor = UIColor.clearColor() cell!.textLabel?.textColor = UIColor.lightGrayColor() cell!.textLabel?.font = UIFont(name: "Avenir", size: 17); let selectedBackgroundView = UIView(frame: CGRectMake(0, 0, cell!.frame.size.width, cell!.frame.size.height)) selectedBackgroundView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2) cell!.selectedBackgroundView = selectedBackgroundView } cell!.textLabel?.text = menuData[indexPath.row]; return cell! } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row == selectedMenuItem) { return } selectedMenuItem = indexPath.row //Present new view controller var vc: UIViewController? switch (indexPath.row) { case 0: vc = UIUtil.getViewControllerFromStoryboard("MainViewController") as! MainViewController break; case 1: let sponsorsVC = UIUtil.getViewControllerFromStoryboard("SponsorsTableViewController") as! SponsorsTableViewController if DataContext.sponsors != nil { sponsorsVC.model = Util.transformGenericArray(DataContext.sponsors!); } vc = sponsorsVC; break; case 2: let promotionsVC = UIUtil.getViewControllerFromStoryboard("PromotionsTableViewController") as! PromotionsTableViewController; if (DataContext.promotions != nil) { promotionsVC.model = Util.transformGenericArray(DataContext.promotions!) } promotionsVC.title = "All Promotions"; vc = promotionsVC; break; default: break; } sideMenuController()?.setContentViewController(vc!); } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
244bd5cd156111af2f413c7edfda1413
34.395161
137
0.631579
5.438662
false
false
false
false
Antidote-for-Tox/Antidote
Antidote/StringExtension.swift
1
2380
// 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 extension String { init(timeInterval: TimeInterval) { var timeInterval = timeInterval let hours = Int(timeInterval / 3600) timeInterval -= TimeInterval(hours * 3600) let minutes = Int(timeInterval / 60) timeInterval -= TimeInterval(minutes * 60) let seconds = Int(timeInterval) if hours > 0 { self.init(format: "%02d:%02d:%02d", hours, minutes, seconds) } else { self.init(format: "%02d:%02d", minutes, seconds) } } init(localized: String, _ arguments: CVarArg...) { let format = NSLocalizedString(localized, tableName: nil, bundle: Bundle.main, value: "", comment: "") self.init(format: format, arguments: arguments) } init(localized: String, comment: String, _ arguments: CVarArg...) { let format = NSLocalizedString(localized, tableName: nil, bundle: Bundle.main, value: "", comment: comment) self.init(format: format, arguments: arguments) } func substringToByteLength(_ length: Int, encoding: String.Encoding) -> String { guard length > 0 else { return "" } var substring = self as NSString while substring.lengthOfBytes(using: encoding.rawValue) > length { let newLength = substring.length - 1 guard newLength > 0 else { return "" } substring = substring.substring(to: newLength) as NSString } return substring as String } func stringSizeWithFont(_ font: UIFont) -> CGSize { return stringSizeWithFont(font, constrainedToSize:CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) } func stringSizeWithFont(_ font: UIFont, constrainedToSize size: CGSize) -> CGSize { let boundingRect = (self as NSString).boundingRect( with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : font], context: nil) return CGSize(width: ceil(boundingRect.size.width), height: ceil(boundingRect.size.height)) } }
mpl-2.0
de796bd99dc89f21990b38d5009cec85
33
146
0.627731
4.712871
false
false
false
false
roambotics/swift
lib/ASTGen/Sources/ASTGen/ASTGen.swift
1
3472
import CASTBridging import SwiftParser import SwiftSyntax extension Array { public func withBridgedArrayRef<T>(_ c: (BridgedArrayRef) -> T) -> T { withUnsafeBytes { buf in c(BridgedArrayRef(data: buf.baseAddress!, numElements: count)) } } } extension UnsafePointer { public var raw: UnsafeMutableRawPointer { UnsafeMutableRawPointer(mutating: self) } } enum ASTNode { case decl(UnsafeMutableRawPointer) case stmt(UnsafeMutableRawPointer) case expr(UnsafeMutableRawPointer) case type(UnsafeMutableRawPointer) case misc(UnsafeMutableRawPointer) var rawValue: UnsafeMutableRawPointer { switch self { case .decl(let ptr): return ptr case .stmt(let ptr): return ptr case .expr(let ptr): return ptr case .type(let ptr): return ptr case .misc(let ptr): return ptr } } func bridged() -> ASTNodeBridged { switch self { case .expr(let e): return ASTNodeBridged(ptr: e, kind: .expr) case .stmt(let s): return ASTNodeBridged(ptr: s, kind: .stmt) case .decl(let d): return ASTNodeBridged(ptr: d, kind: .decl) default: fatalError("Must be expr, stmt, or decl.") } } } /// Little utility wrapper that lets us have some mutable state within /// immutable structs, and is therefore pretty evil. @propertyWrapper class Boxed<Value> { var wrappedValue: Value init(wrappedValue: Value) { self.wrappedValue = wrappedValue } } struct ASTGenVisitor: SyntaxTransformVisitor { typealias ResultType = ASTNode let ctx: UnsafeMutableRawPointer let base: UnsafePointer<UInt8> @Boxed var declContext: UnsafeMutableRawPointer // TODO: this some how messes up the witness table when I uncomment it locally :/ // public func visit<T>(_ node: T?) -> [UnsafeMutableRawPointer]? { // if let node = node { return visit(node) } // return nil // } @_disfavoredOverload public func visit(_ node: SourceFileSyntax) -> ASTNode { fatalError("Use other overload.") } public func visitAny(_ node: Syntax) -> ASTNode { fatalError("Not implemented.") } public func visit(_ node: SourceFileSyntax) -> [UnsafeMutableRawPointer] { let loc = self.base.advanced(by: node.position.utf8Offset).raw var out = [UnsafeMutableRawPointer]() for element in node.statements { let swiftASTNodes = visit(element) switch swiftASTNodes { case .decl(let d): out.append(d) case .stmt(let s): out.append(SwiftTopLevelCodeDecl_createStmt(ctx, declContext, loc, s, loc)) case .expr(let e): out.append(SwiftTopLevelCodeDecl_createExpr(ctx, declContext, loc, e, loc)) default: fatalError("Top level nodes must be decls, stmts, or exprs.") } } return out } } /// Generate AST nodes for all top-level entities in the given source file. @_cdecl("swift_ASTGen_buildTopLevelASTNodes") public func buildTopLevelASTNodes( sourceFilePtr: UnsafePointer<UInt8>, dc: UnsafeMutableRawPointer, ctx: UnsafeMutableRawPointer, outputContext: UnsafeMutableRawPointer, callback: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void ) { sourceFilePtr.withMemoryRebound(to: ExportedSourceFile.self, capacity: 1) { sourceFile in ASTGenVisitor(ctx: ctx, base: sourceFile.pointee.buffer.baseAddress!, declContext: dc) .visit(sourceFile.pointee.syntax) .forEach { callback($0, outputContext) } } }
apache-2.0
fdf9f7bcba6902a6cabc066b8ab0de1a
26.776
91
0.692396
4.249694
false
false
false
false
SouthernBlackNerd/dotfiles
themes/tools/iterm2terminal.swift
1
4360
#!/usr/bin/xcrun swift import AppKit class ThemeConvertor { enum ThemeConvertorError: Error { case NoArguments, UnableToLoadITermFile(URL) } private let iTermFiles: [String] private let iTermColor2TerminalColorMap = [ "Ansi 0 Color": "ANSIBlackColor", "Ansi 1 Color": "ANSIRedColor", "Ansi 2 Color": "ANSIGreenColor", "Ansi 3 Color": "ANSIYellowColor", "Ansi 4 Color": "ANSIBlueColor", "Ansi 5 Color": "ANSIMagentaColor", "Ansi 6 Color": "ANSICyanColor", "Ansi 7 Color": "ANSIWhiteColor", "Ansi 8 Color": "ANSIBrightBlackColor", "Ansi 9 Color": "ANSIBrightRedColor", "Ansi 10 Color": "ANSIBrightGreenColor", "Ansi 11 Color": "ANSIBrightYellowColor", "Ansi 12 Color": "ANSIBrightBlueColor", "Ansi 13 Color": "ANSIBrightMagentaColor", "Ansi 14 Color": "ANSIBrightCyanColor", "Ansi 15 Color": "ANSIBrightWhiteColor", "Background Color": "BackgroundColor", "Foreground Color": "TextColor", "Selection Color": "SelectionColor", "Bold Color": "BoldTextColor", "Cursor Color": "CursorColor", ] required init(iTermFiles: [String]) throws { if iTermFiles.isEmpty { throw ThemeConvertorError.NoArguments } self.iTermFiles = iTermFiles } func run() { for iTermFile in iTermFiles { let iTermFileURL = URL(fileURLWithPath: iTermFile).absoluteURL let folder = iTermFileURL.deletingLastPathComponent() let schemeName = iTermFileURL.deletingPathExtension().lastPathComponent let terminalFileURL = folder.appendingPathComponent("\(schemeName).terminal") do { try convert(scheme: schemeName, fromITermFileAtURL: iTermFileURL, toTerminalFileAtURL: terminalFileURL) } catch ThemeConvertorError.UnableToLoadITermFile(let iTermFileURL) { print("Error: Unable to load \(iTermFileURL)") } catch let error as NSError { print("Error: \(error.description)") } } } private func convert(scheme: String, fromITermFileAtURL src: URL, toTerminalFileAtURL dest: URL) throws { guard let iTermScheme = NSDictionary(contentsOf: src) else { throw ThemeConvertorError.UnableToLoadITermFile(src) } print("Converting \(src) -> \(dest)") var terminalScheme: [String: Any] = [ "name" : scheme, "type" : "Window Settings", "ProfileCurrentVersion" : 2.04, "columnCount": 90, "rowCount": 50, ] if let font = archivedFont(withName: "PragmataPro", size: 14) { terminalScheme["Font"] = font } for (iTermColorKey, iTermColorDict) in iTermScheme { if let iTermColorKey = iTermColorKey as? String, let terminalColorKey = iTermColor2TerminalColorMap[iTermColorKey], let iTermColorDict = iTermColorDict as? NSDictionary, let r = (iTermColorDict["Red Component"] as AnyObject?)?.floatValue, let g = (iTermColorDict["Green Component"] as AnyObject?)?.floatValue, let b = (iTermColorDict["Blue Component"] as AnyObject?)?.floatValue { let color = NSColor(calibratedRed: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: 1) let colorData = NSKeyedArchiver.archivedData(withRootObject: color) terminalScheme[terminalColorKey] = colorData } } NSDictionary(dictionary: terminalScheme).write(to: dest, atomically: true) } private func archivedFont(withName name: String, size: CGFloat) -> Data? { guard let font = NSFont(name: name, size: size) else { return nil } return NSKeyedArchiver.archivedData(withRootObject: font) } } do { let iTermFiles = [String](CommandLine.arguments.dropFirst()) try ThemeConvertor(iTermFiles: iTermFiles).run() } catch ThemeConvertor.ThemeConvertorError.NoArguments { print("Error: no arguments provided") print("Usage: iTermColorsToTerminalColors FILE.ITermColors [...]") }
mit
254a359495390ef34caa7618336f1a8d
37.928571
117
0.609174
4.638298
false
false
false
false
PJayRushton/stats
Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/TextFieldEffects.swift
1
4127
// // TextFieldEffects.swift // TextFieldEffects // // Created by Raúl Riera on 24/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit extension String { /** true if self contains characters. */ var isNotEmpty: Bool { return !isEmpty } } /** A TextFieldEffects object is a control that displays editable text and contains the boilerplates to setup unique animations for text entry and display. You typically use this class the same way you use UITextField. */ open class TextFieldEffects : UITextField { /** The type of animation a TextFieldEffect can perform. - TextEntry: animation that takes effect when the textfield has focus. - TextDisplay: animation that takes effect when the textfield loses focus. */ public enum AnimationType: Int { case textEntry case textDisplay } /** Closure executed when an animation has been completed. */ public typealias AnimationCompletionHandler = (_ type: AnimationType)->() /** UILabel that holds all the placeholder information */ open let placeholderLabel = UILabel() /** Creates all the animations that are used to leave the textfield in the "entering text" state. */ open func animateViewsForTextEntry() { fatalError("\(#function) must be overridden") } /** Creates all the animations that are used to leave the textfield in the "display input text" state. */ open func animateViewsForTextDisplay() { fatalError("\(#function) must be overridden") } /** The animation completion handler is the best place to be notified when the text field animation has ended. */ open var animationCompletionHandler: AnimationCompletionHandler? /** Draws the receiver’s image within the passed-in rectangle. - parameter rect: The portion of the view’s bounds that needs to be updated. */ open func drawViewsForRect(_ rect: CGRect) { fatalError("\(#function) must be overridden") } open func updateViewsForBoundsChange(_ bounds: CGRect) { fatalError("\(#function) must be overridden") } // MARK: - Overrides override open func draw(_ rect: CGRect) { // FIXME: Short-circuit if the view is currently selected. iOS 11 introduced // a setNeedsDisplay when you focus on a textfield, calling this method again // and messing up some of the effects due to the logic contained inside these // methods. // This is just a "quick fix", something better needs to come along. guard isFirstResponder == false else { return } drawViewsForRect(rect) } override open func drawPlaceholder(in rect: CGRect) { // Don't draw any placeholders } override open var text: String? { didSet { if let text = text, text.isNotEmpty { animateViewsForTextEntry() } else { animateViewsForTextDisplay() } } } // MARK: - UITextField Observing override open func willMove(toSuperview newSuperview: UIView!) { if newSuperview != nil { NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidEndEditing), name: NSNotification.Name.UITextFieldTextDidEndEditing, object: self) NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidBeginEditing), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: self) } else { NotificationCenter.default.removeObserver(self) } } /** The textfield has started an editing session. */ @objc open func textFieldDidBeginEditing() { animateViewsForTextEntry() } /** The textfield has ended an editing session. */ @objc open func textFieldDidEndEditing() { animateViewsForTextDisplay() } // MARK: - Interface Builder override open func prepareForInterfaceBuilder() { drawViewsForRect(frame) } }
mit
3afe2cce332198d41c47fc002e5e0cfe
29.761194
214
0.65575
5.277849
false
false
false
false
AKIRA-MIYAKE/SwiftyEvents
SwiftyEventsTests/ListenerTests.swift
3
2493
// // ListenerTests.swift // SwiftyEvents // // Created by MiyakeAkira on 2015/04/02. // Copyright (c) 2015年 Miyake Akira. All rights reserved. // import XCTest import SwiftyEvents class ListenerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testEquatable() { let f = { (str: String) -> Void in print(str) } let la = Listener(function: f) let lb = la let lc = Listener(function: f) XCTAssertEqual(la, lb, "Expect equal") XCTAssertNotEqual(la, lc, "Expect not equal") } func testEquatableInArray() { let f = { (str: String) -> Void in print(str) } let la = Listener(function: f) let lb = Listener(function: f) let arr = [la, lb] let lc = arr[1] XCTAssertEqual(la, arr[0], "Expect equal") XCTAssertEqual(lb, arr[1], "Expect equal") XCTAssertEqual(lb, lc, "Expect equal") } func testExec() { let expectation = self.expectationWithDescription("Execute function") let val = "Value" let f = { (value: String) -> Void in expectation.fulfill() XCTAssertEqual(val, value, "Call function with argument") } let la = Listener(function: f) la.exec(val) waitForExpectationsWithTimeout(2.0, handler: nil) } func testArgumentTypes() { let la = Listener(function: { (value: Int) -> Void in XCTAssertEqual(1, value, "Call function with Int") }) la.exec(1) let lb = Listener(function: { (value: CGRect) -> Void in XCTAssertEqual(CGRectMake(10, 10, 10, 10), value, "Call functin with Coordinate") }) lb.exec(CGRectMake(10, 10, 10, 10)) let lc = Listener(function: { (value: (Int) -> Int) -> Void in XCTAssertEqual(10, value(5), "Call function with Function") }) let function = { (value: Int) -> Int in return value * 2 } lc.exec(function) } }
mit
09bfb05c38e8f2fbfc2f58b28d1596bb
26.373626
111
0.539944
4.362522
false
true
false
false
jkufver/NSSpainEnteranceTracker
NSSpainEnteranceTracker/BeaconSignalDispatcher.swift
1
5050
// // BeaconSignalDispatcher.swift // NSSpainEnteranceTracker // // Created by Dorin Danciu on 17/09/14. // Copyright (c) 2014 Jens Kufver. All rights reserved. // import Foundation import CoreLocation enum LocationRelatedToVenue : Int{ case Unknown case Inside case Outside case InBetween func simpleDescription() -> String { switch self { case .Unknown: return "Unknown" case .Inside: return "Inside" case .Outside: return "Outside" case .InBetween: return "InBetween" } } } protocol BeaconSignalDispatcherDelegate : NSObjectProtocol { func beaconSignalDispatcherDidSignalEventOfType(eventType: LocationRelatedToVenue, location:String) } private let _beaconSignalDispatcherSingletonInstance = BeaconSignalDispatcher() class BeaconSignalDispatcher: NSObject, MonitoringEngineDelegate { var beacons = Array<BeaconActivity>() var delegates = Array<BeaconSignalDispatcherDelegate>() var signals = Array<AnyObject>() override init() { super.init() loadBeacons() } class var sharedInstance: BeaconSignalDispatcher { return _beaconSignalDispatcherSingletonInstance } func registerDelegate(item:BeaconSignalDispatcherDelegate) { delegates.append(item) } func removeDelegate(item:BeaconSignalDispatcherDelegate) { for (index, element) in enumerate(delegates) { if element === item { delegates.removeAtIndex(index) } } } func dequeue(){ if let firstObj: AnyObject = signals.first { signals.removeAtIndex(0) } } func enqueue (item : AnyObject){ if signals.count > 20 { dequeue() } signals.append(item) } func loadBeacons () { beacons.append(BeaconActivity()) beacons.append(BeaconActivity()) } func beaconForMinor(beacons: [AnyObject]!, minor: Int)->(AnyObject?) { for (index, element) in enumerate(beacons) { if element.minor == minor { return element } } return nil } func notifyObserversWithEventTypeAndLocation(aType:LocationRelatedToVenue, location:String) { println("Notification Sent! type: \(aType.simpleDescription()) | location: \(location)") for (index, element) in enumerate(delegates) { element.beaconSignalDispatcherDidSignalEventOfType(aType, location: location) } } // func handleBeaconSignal(beacon:BeaconActivity) { // if let prevBeacon = beaconForMinor(beacon.minor) { // if prevBeacon.proximity == beacon.proximity { // return // } // // switch prevBeacon.proximity { //// case .Immediate: //// notifyObserversWithEventTypeAndLocation(.ExitImmediate, location: "\(beacon.minor)") // // case .Near: // notifyObserversWithEventTypeAndLocation(.ExitNear, location: "\(beacon.minor)") // default: // break // } // // switch beacon.proximity { //// case .Immediate: //// notifyObserversWithEventTypeAndLocation(.EnterImmediate, location: "\(beacon.minor)") // // case .Near: // notifyObserversWithEventTypeAndLocation(.EnterNear, location: "\(beacon.minor)") // default: // break // } // // // update previous beacon // beacons[beacon.minor] = beacon; // } else { // beacons[beacon.minor] = beacon; // } // } func monitoringEngine(engine: MonitoringEngine!, didRangeBeacons beacons: [AnyObject]!) { var outside = beaconForMinor(beacons, minor: BEACON_OUTSIDE_MINOR) as CLBeacon? var inside = beaconForMinor(beacons, minor: BEACON_INSIDE_MINOR) as CLBeacon? if outside == nil && inside == nil { return } if ((outside != nil && inside == nil)||(outside!.accuracy < inside!.accuracy)) { // outside println("outside") notifyObserversWithEventTypeAndLocation(.Outside, location: "Venue") } else if ((outside == nil && inside != nil)||(outside!.accuracy > inside!.accuracy)) { // inside println("inside") notifyObserversWithEventTypeAndLocation(.Inside, location: "Venue") } else { // in between println("in between") notifyObserversWithEventTypeAndLocation(.Unknown, location: "Venue") } // for (index, element) in enumerate(beacons) { // var beaconActivity = BeaconActivity(beacon: element as CLBeacon) // handleBeaconSignal(beaconActivity) // } } }
mit
9c437baf9606b90b2834527641754923
30.761006
108
0.57703
4.777673
false
false
false
false
PerrchicK/swift-app
SomeApp/SomeApp/Logic/Game/TicTacToeGame.swift
1
4761
// // TicTacToeGame.swift // SomeApp // // Created by Perry on 2/23/16. // Copyright © 2016 PerrchicK. All rights reserved. // import Foundation protocol TicTacToeGameDelegate: GameDelegate { } class TicTacToeGame: Game { internal var currentPlayer: Player weak internal var delegate: GameDelegate? struct Configuration { static let RowsCount = 3 static let ColumnsCount = Configuration.RowsCount static let MaxMovesInSequence = Configuration.RowsCount } enum TicTacToePlayer: Player { // Enums don't must to inherit from anywhere, but it's helpful case X case O func intValue() -> Int { // return TicTacToePlayer.X == self ? 1 : -1 return (TicTacToePlayer.X == self).if(then: 1, else: -1) } func stringValue() -> String { // return TicTacToePlayer.X == self ? "X" : "O" return (TicTacToePlayer.X == self).if(then: "X", else: "O") } } // Computed property fileprivate var isGameEnabled: Bool { // Using 'guard' keyword to ensure that the delegate exists (not null): guard let delegate = delegate else { return false } // If exists: Make a new (and not optional!) object and continue // If it doesn't exist: do nothing and return 'false' return delegate.isGameEnabled(self) } fileprivate lazy var matrix = Array<[Int?]>(repeating: Array<Int?>(repeating: nil, count: Configuration.RowsCount), count: Configuration.ColumnsCount) init() { currentPlayer = TicTacToePlayer.X } internal func playMove(player: Player, row: Int, column: Int) { // Using 'guard' statement to ensure conditions guard isGameEnabled && matrix[row][column] == nil else { return } matrix[row][column] = player.intValue() if let winner = checkWinner() { delegate?.game(self, finishedWithWinner: winner) } else { switchTurns() } delegate?.game(self, playerMadeMove: player, row: row, column: column) } fileprivate func switchTurns() { guard let _currentPlayer = currentPlayer as? TicTacToePlayer else { return } currentPlayer = _currentPlayer == TicTacToePlayer.X ? TicTacToePlayer.O : TicTacToePlayer.X } fileprivate func checkWinner() -> Player? { var winner: Player? = nil var diagonalSequenceCounter = 0 var reverseDiagonalSequenceCounter = 0 var verticalSequenceCounter = Array<Int>(repeating: 0, count: Configuration.MaxMovesInSequence) // Or: var verticalSequenceCounter = [0,0,0] for row in 0...Configuration.RowsCount - 1 { // Using 'guard' keyword for optimization in runtime, skips redundant loops guard winner == nil else { return winner } // Count \ let diagonalIndex = row if let moveInDiagonalSequence = matrix[diagonalIndex][diagonalIndex] { if moveInDiagonalSequence == currentPlayer.intValue() { // Removed on Swift 3.0: // diagonalSequenceCounter++ diagonalSequenceCounter += 1 } } // Count / let reverseDiagonalIndex = Configuration.RowsCount - row - 1 if let moveInReverseDiagonalSequence = matrix[row][reverseDiagonalIndex] { if moveInReverseDiagonalSequence == currentPlayer.intValue() { // Removed on Swift 3.0: // reverseDiagonalSequenceCounter++ reverseDiagonalSequenceCounter += 1 } } var horizontalSequenceCounter = 0 for column in 0...Configuration.ColumnsCount - 1 { if let moveInRow = matrix[row][column] { if moveInRow == currentPlayer.intValue() { // Count - horizontalSequenceCounter += 1 // Count | verticalSequenceCounter[column] += currentPlayer.intValue() } } } if [horizontalSequenceCounter, diagonalSequenceCounter, reverseDiagonalSequenceCounter].contains(Configuration.MaxMovesInSequence) { // 3 in an horozintal / diagonal row winner = currentPlayer } else if verticalSequenceCounter.contains(-Configuration.MaxMovesInSequence) || verticalSequenceCounter.contains(Configuration.MaxMovesInSequence) { // 3 in a vertical row winner = currentPlayer } } return winner } func restart() { } }
apache-2.0
0bf9a77db26551bbca6ccc3ac3c95675
34.789474
161
0.590756
4.937759
false
true
false
false
carabina/DDMathParser
MathParser/RewriteRule+Defaults.swift
2
2840
// // RewriteRule+Defaults.swift // DDMathParser // // Created by Dave DeLong on 8/25/15. // // import Foundation extension RewriteRule { public static let defaultRules: Array<RewriteRule> = [ try? RewriteRule(predicate: "0 + __exp1", template: "__exp1"), try? RewriteRule(predicate: "__exp1 + 0", template: "__exp1"), try? RewriteRule(predicate: "__exp1 + __exp1", template: "2 * __exp1"), try? RewriteRule(predicate: "__exp1 - __exp1", template: "0"), try? RewriteRule(predicate: "1 * __exp1", template: "__exp1"), try? RewriteRule(predicate: "__exp1 * 1", template: "__exp1"), try? RewriteRule(predicate: "__exp1 / 1", template: "__exp1"), try? RewriteRule(predicate: "__exp1 * __exp1", template: "__exp1 ** 2"), try? RewriteRule(predicate: "__num1 * __var1", template: "__var1 * __num1"), try? RewriteRule(predicate: "0 * __exp1", template: "0"), try? RewriteRule(predicate: "__exp1 * 0", template: "0"), try? RewriteRule(predicate: "--__exp1", template: "__exp1"), try? RewriteRule(predicate: "abs(-__exp1)", template: "abs(__exp1)"), try? RewriteRule(predicate: "exp(__exp1) * exp(__exp2)", template: "exp(__exp1 + __exp2)"), try? RewriteRule(predicate: "(__exp1 ** __exp3) * (__exp2 ** __exp3)", template: "(__exp1 * __exp2) ** __exp3"), try? RewriteRule(predicate: "__exp1 ** 0", template: "1"), try? RewriteRule(predicate: "__exp1 ** 1", template: "__exp1"), try? RewriteRule(predicate: "sqrt(__exp1 ** 2)", template: "abs(__exp1)"), try? RewriteRule(predicate: "dtor(rtod(__exp1))", template: "__exp1"), try? RewriteRule(predicate: "rtod(dtor(__exp1))", template: "__exp1"), //division try? RewriteRule(predicate: "__exp1 / __exp1", condition: "__exp1 != 0", template: "1"), try? RewriteRule(predicate: "(__exp1 * __exp2) / __exp2", condition: "__exp2 != 0", template: "__exp1"), try? RewriteRule(predicate: "(__exp2 * __exp1) / __exp2", condition: "__exp2 != 0", template: "__exp1"), try? RewriteRule(predicate: "__exp2 / (__exp2 * __exp1)", condition: "__exp2 != 0", template: "1/__exp1"), try? RewriteRule(predicate: "__exp2 / (__exp1 * __exp2)", condition: "__exp2 != 0", template: "1/__exp1"), //exponents and roots try? RewriteRule(predicate: "nthroot(__exp1, 1)", template: "__exp1"), try? RewriteRule(predicate: "nthroot(pow(__exp1, __exp2), __exp2)", condition: "__exp2 % 2 == 0", template: "abs(__exp1)"), try? RewriteRule(predicate: "nthroot(pow(__exp1, __exp2), __exp2)", condition: "__exp2 % 2 == 1", template: "__exp1"), try? RewriteRule(predicate: "abs(__exp1)", condition: "__exp1 >= 0", template: "__exp1") ].flatMap { $0 } }
mit
339e55ead267204ccabcb84b61bb3977
54.686275
131
0.559859
3.356974
false
false
false
false
tarunon/mstdn
MstdnKit/Sources/Models/Tag.swift
1
777
// // Tag.swift // mstdn // // Created by tarunon on 2017/04/24. // Copyright © 2017年 tarunon. All rights reserved. // import Foundation import Himotoki import RealmSwift public final class Tag: Object { public var name: String = "" public var url: URL = URL(fileURLWithPath: "/") public override class func primaryKey() -> String? { return "name" } public class func from(name: String, url: URL) -> Tag { let tag = Tag() tag.name = name tag.url = url return tag } } extension Tag: Decodable { public static func decode(_ e: Extractor) throws -> Tag { return try Tag.from( name: e <| "name", url: URL.Transformers.string.apply(e <| "url") ) } }
mit
964eadc38d800b4f2ac48ab0f5f4f944
20.5
61
0.574935
3.812808
false
false
false
false
aschuch/StatefulViewController
StatefulViewController/ViewStateMachine.swift
1
8058
// // ViewStateMachine.swift // StatefulViewController // // Created by Alexander Schuch on 30/07/14. // Copyright (c) 2014 Alexander Schuch. All rights reserved. // import UIKit /// Represents the state of the view state machine public enum ViewStateMachineState : Equatable { case none // No view shown case view(String) // View with specific key is shown } public func == (lhs: ViewStateMachineState, rhs: ViewStateMachineState) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.view(let lName), .view(let rName)): return lName == rName default: return false } } /// /// A state machine that manages a set of views. /// /// There are two possible states: /// * Show a specific placeholder view, represented by a key /// * Hide all managed views /// public class ViewStateMachine { fileprivate var viewStore: [String: UIView] fileprivate let queue = DispatchQueue(label: "com.aschuch.viewStateMachine.queue", attributes: []) /// An invisible container view that gets added to the view. /// The placeholder views will be added to the containerView. /// /// view /// \_ containerView /// \_ error | loading | empty view private lazy var containerView: UIView = { // Setup invisible container view. // This is a workaround to make sure the placeholder views are shown in instances // of UITableViewController and UICollectionViewController. let containerView = PassthroughView(frame: .zero) containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] containerView.backgroundColor = .clear return containerView }() /// The view that should act as the superview for any added views public let view: UIView /// The current display state of views public fileprivate(set) var currentState: ViewStateMachineState = .none /// The last state that was enqueued public fileprivate(set) var lastState: ViewStateMachineState = .none // MARK: Init /// Designated initializer. /// /// - parameter view: The view that should act as the superview for any added views /// - parameter states: A dictionary of states /// /// - returns: A view state machine with the given views for states /// public init(view: UIView, states: [String: UIView]?) { self.view = view viewStore = states ?? [String: UIView]() } /// - parameter view: The view that should act as the superview for any added views /// /// - returns: A view state machine /// public convenience init(view: UIView) { self.init(view: view, states: nil) } // MARK: Add and remove view states /// - returns: the view for a given state public func viewForState(_ state: String) -> UIView? { return viewStore[state] } /// Associates a view for the given state public func addView(_ view: UIView, forState state: String) { viewStore[state] = view } /// Removes the view for the given state public func removeViewForState(_ state: String) { viewStore[state] = nil } // MARK: Subscripting public subscript(state: String) -> UIView? { get { return viewForState(state) } set(newValue) { if let value = newValue { addView(value, forState: state) } else { removeViewForState(state) } } } // MARK: Switch view state /// Adds and removes views to and from the `view` based on the given state. /// Animations are synchronized in order to make sure that there aren't any animation gliches in the UI /// /// - parameter state: The state to transition to /// - parameter animated: true if the transition should fade views in and out /// - parameter campletion: called when all animations are finished and the view has been updated /// public func transitionToState(_ state: ViewStateMachineState, animated: Bool = true, completion: (() -> ())? = nil) { lastState = state queue.async { [weak self] in guard let strongSelf = self else { return } if state == strongSelf.currentState { return } // Suspend the queue, it will be resumed in the completion block strongSelf.queue.suspend() strongSelf.currentState = state let c: () -> () = { strongSelf.queue.resume() completion?() } // Switch state and update the view DispatchQueue.main.sync { switch state { case .none: strongSelf.hideAllViews(animated: animated, completion: c) case .view(let viewKey): strongSelf.showView(forKey: viewKey, animated: animated, completion: c) } } } } // MARK: Private view updates fileprivate func showView(forKey state: String, animated: Bool, completion: (() -> ())? = nil) { // Add the container view containerView.frame = view.bounds view.addSubview(containerView) let store = viewStore if let newView = store[state] { newView.alpha = animated ? 0.0 : 1.0 let insets = (newView as? StatefulPlaceholderView)?.placeholderViewInsets() ?? UIEdgeInsets() // Add new view using AutoLayout newView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(newView) let metrics = ["top": insets.top, "bottom": insets.bottom, "left": insets.left, "right": insets.right] let views = ["view": newView] let hConstraints = NSLayoutConstraint.constraints(withVisualFormat: "|-left-[view]-right-|", options: [], metrics: metrics, views: views) let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-top-[view]-bottom-|", options: [], metrics: metrics, views: views) containerView.addConstraints(hConstraints) containerView.addConstraints(vConstraints) } let animations: () -> () = { if let newView = store[state] { newView.alpha = 1.0 } } let animationCompletion: (Bool) -> () = { _ in for (key, view) in store { if !(key == state) { view.removeFromSuperview() } } completion?() } animateChanges(animated: animated, animations: animations, completion: animationCompletion) } fileprivate func hideAllViews(animated: Bool, completion: (() -> ())? = nil) { let store = viewStore let animations: () -> () = { for (_, view) in store { view.alpha = 0.0 } } let animationCompletion: (Bool) -> () = { [weak self] _ in for (_, view) in store { view.removeFromSuperview() } // Remove the container view self?.containerView.removeFromSuperview() completion?() } animateChanges(animated: animated, animations: animations, completion: animationCompletion) } fileprivate func animateChanges(animated: Bool, animations: @escaping () -> (), completion: ((Bool) -> Void)?) { if animated { UIView.animate(withDuration: 0.3, animations: animations, completion: completion) } else { completion?(true) } } } private class PassthroughView: UIView { fileprivate override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { for view in subviews { if !view.isHidden && view.alpha > 0 && view.isUserInteractionEnabled && view.point(inside: convert(point, to: view), with:event) { return true } } return false } }
mit
55f996f92f83070d887daf8fd753553e
31.756098
151
0.595805
4.857143
false
false
false
false
tktsubota/CareKit
testing/OCKTest/OCKTest/BarChartViewController.swift
2
6472
/* Copyright (c) 2016, Apple Inc. 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(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. 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 OWNER 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 CareKit class BarChartViewController: UIViewController, OCKGroupedBarChartViewDataSource { @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() let chartWidth = UIScreen.main.bounds.width - 20 scrollView.contentSize = CGSize(width: self.view.frame.width, height: 2000) let multiColorChartView = OCKGroupedBarChartView.init(frame: CGRect(x: 5, y: 0, width: chartWidth, height: 600)) multiColorChartView.accessibilityLabel = "multiColorChartView" multiColorChartView.animate(withDuration: 4) multiColorChartView.backgroundColor = UIColor.init(hue: 0.85, saturation: 0.1, brightness: 0.8, alpha: 0.3) multiColorChartView.dataSource = self scrollView.addSubview(multiColorChartView) let emptyChartView = OCKGroupedBarChartView.init(frame: CGRect(x: 5, y: 610, width: chartWidth, height: 20)) emptyChartView.accessibilityLabel = "emptyChartView" emptyChartView.backgroundColor = UIColor.init(hue: 0.1, saturation: 0.8, brightness: 0.5, alpha: 0.8) scrollView.addSubview(emptyChartView) let twoSeriesChartView = OCKGroupedBarChartView.init(frame: CGRect(x: 5, y: 640, width: chartWidth, height: 500)) twoSeriesChartView.accessibilityLabel = "twoSeriesChartView" twoSeriesChartView.backgroundColor = UIColor.init(hue: 0.05, saturation: 0.1, brightness: 0.9, alpha: 0.3) twoSeriesChartView.dataSource = self twoSeriesChartView.animate(withDuration: 1) scrollView.addSubview(twoSeriesChartView) let negativeValuesChartView = OCKGroupedBarChartView.init(frame: CGRect(x: 5, y: 1200, width: chartWidth, height: 600)) negativeValuesChartView.backgroundColor = UIColor.init(hue: 0.66, saturation: 0.2, brightness: 0.9, alpha: 0.2) negativeValuesChartView.accessibilityLabel = "negativeValuesChartView" negativeValuesChartView.dataSource = self scrollView.addSubview(negativeValuesChartView) } func numberOfDataSeries(in chartView: OCKGroupedBarChartView) -> Int { let chartName = chartView.accessibilityLabel if chartName == "multiColorChartView" { return 30 } else if chartName == "negativeValuesChartView" { return 4 } else { return 2 } } func numberOfCategoriesPerDataSeries(in chartView: OCKGroupedBarChartView) -> Int { let chartName = chartView.accessibilityLabel if chartName == "multiColorChartView" { return 1 } else if chartName == "negativeValuesChartView" { return 5 } else { return 8 } } func maximumScaleRangeValue(of chartView: OCKGroupedBarChartView) -> NSNumber? { if chartView.accessibilityLabel == "multiColorChartView" { return NSNumber(value: 1500) } return nil } func minimumScaleRangeValue(of chartView: OCKGroupedBarChartView) -> NSNumber? { if chartView.accessibilityLabel == "negativeValuesChartView" { return NSNumber(value: -40) } return nil } func chartView(_ chartView: OCKGroupedBarChartView, valueForCategoryAt categoryIndex: UInt, inDataSeriesAt dataSeriesIndex: UInt) -> NSNumber { let chartName = chartView.accessibilityLabel if chartName == "multiColorChartView" { return NSNumber(value: (categoryIndex + 1) * (dataSeriesIndex*dataSeriesIndex + 1)) } else if chartName == "negativeValuesChartView" { var value:Int = (Int)((categoryIndex + 1) * (dataSeriesIndex + 1)) value = value * -1 return NSNumber(value: value) } else { return NSNumber(value: Float(categoryIndex) * 0.04) } } func chartView(_ chartView: OCKGroupedBarChartView, titleForCategoryAt categoryIndex: UInt) -> String? { return "Title" + String(categoryIndex) } func chartView(_ chartView: OCKGroupedBarChartView, subtitleForCategoryAt categoryIndex: UInt) -> String? { return String(categoryIndex) + " SubTitle" } func chartView(_ chartView: OCKGroupedBarChartView, colorForDataSeriesAt dataSeriesIndex: UInt) -> UIColor { let hue = ((CGFloat)(dataSeriesIndex + 1)) * 3 / 100.0 return UIColor.init(hue: hue, saturation: 0.7, brightness: 0.8, alpha: 1) } func chartView(_ chartView: OCKGroupedBarChartView, nameForDataSeriesAt dataSeriesIndex: UInt) -> String { return String(dataSeriesIndex) + " Series" } func chartView(_ chartView: OCKGroupedBarChartView, valueStringForCategoryAt categoryIndex: UInt, inDataSeriesAt dataSeriesIndex: UInt) -> String? { return "Val: " + String(describing: chartView.dataSource!.chartView(chartView, valueForCategoryAt: categoryIndex, inDataSeriesAt: dataSeriesIndex)) } }
bsd-3-clause
8353c566c88b355c73ae95559f871445
50.776
155
0.72296
4.603129
false
false
false
false
yotao/YunkuSwiftSDKTEST
YunkuSwiftSDK/YunkuSwiftSDK/Class/Data/FileOperationData.swift
1
1113
// // Created by Brandon on 15/6/1. // Copyright (c) 2015 goukuai. All rights reserved. // import Foundation class FileOperationData :BaseData { static let stateNoupload = 1 static let keyState = "state" static let keyHash = "hash" static let keyVersion = "version" static let keyServer = "server" var state:Int! = 0 var uuidHash:String! = "" var version:String! = "" var server:String! = "" class func create (_ dic:Dictionary<String,AnyObject>,code:Int) -> FileOperationData { let data = FileOperationData() data.code = code if code == HTTPStatusCode.ok.rawValue { data.state = dic[keyState] as? Int data.uuidHash = dic[keyHash] as? String data.server = dic[keyServer] as? String }else { if let errorMsg = dic[keyErrormsg] as? String { data.errorMsg = errorMsg } if let errorcode = dic[keyErrorcode] as? Int { data.errorCode = errorcode } } return data } }
mit
a1146b7198458b3d7cc7afcbfcd3a472
24.883721
90
0.560647
4.168539
false
false
false
false
pengzishang/AMJBluetooth
AMJBluetoothDemo/blueToothTest/Union/LockUnionList.swift
1
6563
// // LockUnionList.swift // blueToothTest // // Created by pzs on 2017/7/3. // Copyright © 2017年 彭子上. All rights reserved. // import UIKit class LockUnionList: UITableViewController { var deviceInfo = Dictionary<String, Any>.init() var devices = Array<Dictionary<String, String>>.init() var globalBtn = UIButton.init() override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { if UserDefaults.standard.array(forKey: self.deviceID(with: self.deviceInfo)) as? Array<Dictionary<String, String>> != nil { devices = UserDefaults.standard.array(forKey: self.deviceID(with: self.deviceInfo)) as! Array<Dictionary<String, String>> self.tableView.reloadData() } } func deviceFullID(with infoDic:Dictionary<String, Any>) -> String! { let advdic=infoDic[AdvertisementData] as! NSDictionary return advdic.object(forKey: "kCBAdvDataLocalName") as! String? } func deviceID(with infoDic:Dictionary<String, Any>) -> String! { let advdic=infoDic[AdvertisementData] as! NSDictionary let deviceID = advdic.object(forKey: "kCBAdvDataLocalName") as! String let indexOfDeviceID = deviceID.index(deviceID.startIndex, offsetBy: 7) let deviceMACID = deviceID.substring(from: indexOfDeviceID) return deviceMACID } @IBAction func relatLock(_ sender: UIButton) { self.performSegue(withIdentifier: "lockList", sender: nil) } @IBAction func deleteAll(_ sender: UIButton) { let lockID = self.deviceID(with: self.deviceInfo) var command :NSString = "003001" command = command.full(withLengthCountBehide: 30)! as NSString BluetoothManager.getInstance()?.sendByteCommand(with: command as String, deviceID: lockID!, sendType: .lock, success: { (data) in }, fail: { (failCode) -> UInt in ToolsFuntion.openErrorAlert(withTarget: self, errorCode: failCode) return 0 }) } @IBAction func addUnion(_ sender: UIButton) { self.performSegue(withIdentifier: "lockaddunion", sender: nil) } @IBAction func record(_ sender: UIButton) { sender.isHidden = true let acitionIndicator = sender.superview?.superview?.viewWithTag(1003) as! UIActivityIndicatorView acitionIndicator.startAnimating() let deviceIndex = (sender.superview?.superview?.tag)! - 10000 let lockID = self.deviceID(with: self.deviceInfo) var deviceID = (sender.superview?.superview?.viewWithTag(1001) as! UILabel).text! as NSString deviceID = deviceID.substring(from: 7) as NSString var command = "003000" + (devices[deviceIndex]["deviceStatus"]! as NSString ).full(withLengthCount: 3) command.append(NSString.convertMacID(deviceID as String!, reversed: true)) command.append("255") BluetoothManager.getInstance()?.sendByteCommand(with: command, deviceID: lockID!, sendType: .lock, success: { (data) in sender.isHidden = false acitionIndicator.stopAnimating() }, fail: { (failCode) -> UInt in ToolsFuntion.openErrorAlert(withTarget: self, errorCode: failCode) sender.isHidden = false acitionIndicator.stopAnimating() return 0 }) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return devices.count + 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == devices.count{ return 100 } else { return 60 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == devices.count { let cell = tableView.dequeueReusableCell(withIdentifier: "func", for: indexPath) let deviceInfoID = cell.viewWithTag(1001) as! UILabel deviceInfoID.text = "当前取电器: " + self.deviceFullID(with: deviceInfo) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "item", for: indexPath) cell.tag = 10000 + indexPath.row let deviceID = cell.viewWithTag(1001) as! UILabel let deviceStatus = cell.viewWithTag(1002) as! UILabel deviceID.text = devices[indexPath.row]["deviceID"] deviceStatus.text = devices[indexPath.row]["deviceStatus"] return cell } } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.row != devices.count { return true } return false } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source devices.remove(at: indexPath.row) UserDefaults.standard.set(devices, forKey: self.deviceID(with: self.deviceInfo)) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } // 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?) { if segue.identifier == "lockaddunion" { let target :LockAddUnionController = segue.destination as! LockAddUnionController target.devices = self.devices target.deviceInfo = self.deviceInfo } else if segue.identifier == "lockList" { let target :LockListController = segue.destination as! LockListController target.deviceInfo = self.deviceInfo } // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } }
mit
f69818d18233f422887d324f76ed41b4
38.185629
138
0.636919
4.762737
false
false
false
false
johnpatrickmorgan/Sparse
Sources/SparseTests/Core/ParserCombinatorsTests.swift
1
7029
// // ParserCombinatorsTests.swift // Sparse // // Created by John Morgan on 07/12/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import Quick import Nimble @testable import Sparse class ParserCombinatorsSpec: QuickSpec { override func spec() { describe("the 'then' function") { let parser = character("X").then(character("Y")) it("should parse good input correctly") { let input = "XY" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output.0).to(equal("X")) expect(output.1).to(equal("Y")) expect(stream.isAtEnd).to(equal(true)) } } it("should fail on bad inputs") { let badInputs = ["Xy", "X", "YY", "Xray"] for input in badInputs { let stream = Stream(input) _ = shouldThrow({ _ = try parser.parse(stream) }) } } } describe("the 'skipThen' function") { let parser = character("X").skipThen(character("Y")) it("should parse good input correctly") { let input = "XY" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("Y")) expect(stream.isAtEnd).to(equal(true)) } } it("should fail on bad inputs") { let badInputs = ["Xy", "X", "YY", "Xray"] for input in badInputs { let stream = Stream(input) _ = shouldThrow({ _ = try parser.parse(stream) }) } } } describe("the 'thenSkip' function") { let parser = character("X").thenSkip(character("Y")) it("should parse good input correctly") { let input = "XY" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("X")) expect(stream.isAtEnd).to(equal(true)) } } it("should fail on bad inputs") { let badInputs = ["Xy", "X", "YY", "Xray"] for input in badInputs { let stream = Stream(input) _ = shouldThrow({ _ = try parser.parse(stream) }) } } } describe("the 'butNot' function") { let parser = character(in: .alphanumerics).butNot(string("XX")) it("should parse valid input") { let input = "hello" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("h")) expect(String(stream.remainder)).to(equal("ello")) } } it("should fail on invalid input") { let input = "XX" let stream = Stream(input) _ = shouldThrow({ try parser.parse(stream) }) } } describe("the 'while' function") { let parser = many(character(in: .alphanumerics), while: characterNot("V")) it("should stop parsing due to terminating parser") { let input = "helloVworld" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal(["h","e","l","l","o"])) expect(String(stream.remainder)).to(equal("Vworld")) } } it("should succeed if the terminator is not found") { let input = "hello" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal(["h","e","l","l","o"])) expect(stream.isAtEnd).to(equal(true)) } } it("should stop parsing due to the original parser") { let input = "hello world" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal(["h","e","l","l","o"])) expect(String(stream.remainder)).to(equal(" world")) } } } describe("the 'otherwise' function") { let parser = character("V").otherwise(character("X")) it("should correctly parse with the first parser") { let input = "VR" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("V")) expect(String(stream.remainder)).to(equal("R")) } } it("should correctly parse with the second parser") { let input = "XR" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("X")) expect(String(stream.remainder)).to(equal("R")) } } it("should fail if both parsers fail") { let input = "JR" let stream = Stream(input) _ = shouldThrow({ _ = try parser.parse(stream) }) } } describe("the 'otherwiseSkip' function") { let parser = character("V").otherwiseSkip(character("X")) it("should correctly parse with the first parser") { let input = "VR" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("V")) let remainder = String(stream.remainder) expect(remainder).to(equal("R")) } } it("should correctly skip the second parser") { let input = "XR" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(beNil()) expect(String(stream.remainder)).to(equal("R")) } } it("should fail if both parsers fail") { let input = "JR" let stream = Stream(input) _ = shouldThrow({ _ = try parser.parse(stream) }) } } } }
mit
37080702ff6399f33d8fc8db630a5ae2
38.044444
86
0.453756
4.873786
false
false
false
false
danielmartin/swift
test/SILOptimizer/capturepromotion-wrong-lexicalscope.swift
1
2390
// Make sure project_box gets assigned the correct lexical scope when we create it. // RUN: %target-swift-frontend -primary-file %s -Onone -emit-sil -Xllvm -sil-print-after=capture-promotion -Xllvm \ // RUN: -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s // CHECK: sil hidden [ossa] @$s4null19captureStackPromoteSiycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> Int { // CHECK: bb0: // CHECK: %0 = alloc_box ${ var Int }, var, name "x", loc {{.*}}:32:7, scope 3 // CHECK: %1 = project_box %0 : ${ var Int }, 0, loc {{.*}}:32:7, scope 3 // CHECK: %2 = metatype $@thin Int.Type, loc {{.*}}:32:11, scope 3 // CHECK: %3 = integer_literal $Builtin.IntLiteral, 1, loc {{.*}}:32:11, scope 3 // CHECK: %4 = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int, loc {{.*}}:32:11, scope 3 // CHECK: %5 = apply %4(%3, %2) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int, loc {{.*}}:32:11, scope 3 // CHECK: store %5 to [trivial] %1 : $*Int, loc {{.*}}:32:11, scope 3 // CHECK: %7 = copy_value %0 : ${ var Int }, loc {{.*}}:33:11, scope 3 // CHECK: %8 = project_box %7 : ${ var Int }, 0, loc {{.*}}:33:11, scope 3 // CHECK: mark_function_escape %1 : $*Int, loc {{.*}}:33:11, scope 3 // CHECK: %10 = function_ref @$s4null19captureStackPromoteSiycyFSiycfU_Tf2i_n : $@convention(thin) (Int) -> Int, loc {{.*}}:33:11, scope 3 // CHECK: %11 = load [trivial] %8 : $*Int, loc {{.*}}:33:11, scope 3 // CHECK: destroy_value %7 : ${ var Int }, loc {{.*}}:33:11, scope 3 // CHECK: %13 = partial_apply [callee_guaranteed] %10(%11) : $@convention(thin) (Int) -> Int, loc {{.*}}:33:11, scope 3 // CHECK: debug_value %13 : $@callee_guaranteed () -> Int, let, name "f", loc {{.*}}:33:7, scope 3 // CHECK: %15 = begin_borrow %13 : $@callee_guaranteed () -> Int, loc {{.*}}:34:10, scope 3 // CHECK: %16 = copy_value %15 : $@callee_guaranteed () -> Int, loc {{.*}}:34:10, scope 3 // CHECK: end_borrow %15 : $@callee_guaranteed () -> Int // CHECK: destroy_value %13 : $@callee_guaranteed () -> Int, loc {{.*}}:35:1, scope 3 // CHECK: destroy_value %0 : ${ var Int }, loc {{.*}}:35:1, scope 3 // CHECK: return %16 : $@callee_guaranteed () -> Int, loc {{.*}}:34:3, scope 3 // CHECK: } func captureStackPromote() -> () -> Int { var x = 1 let f = { x } return f }
apache-2.0
5df5b5b8754507c3132c3ec2f16af936
67.285714
162
0.584519
3.075933
false
false
false
false
qvacua/vimr
VimR/VimR/ShortcutsPref.swift
1
13042
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import PureLayout import RxSwift import ShortcutRecorder final class ShortcutValueTransformer: ValueTransformer { static let shared = ShortcutValueTransformer() override class func allowsReverseTransformation() -> Bool { true } /// Data to Shortcut override func transformedValue(_ value: Any?) -> Any? { guard let value, let data = value as? Data else { return nil } return try? NSKeyedUnarchiver.unarchivedObject(ofClass: Shortcut.self, from: data) } /// Shortcut to Data override func reverseTransformedValue(_ value: Any?) -> Any? { guard let value, let shortcut = value as? Shortcut else { return nil } return try? NSKeyedArchiver.archivedData(withRootObject: shortcut, requiringSecureCoding: true) } } final class ShortcutsPref: PrefPane, UiComponent, NSOutlineViewDelegate, RecorderControlDelegate { typealias StateType = AppState @objc dynamic var content = [ShortcutItem]() override var displayName: String { "Shortcuts" } override var pinToContainer: Bool { true } weak var shortcutService: ShortcutService? { didSet { self.updateShortcutService() } } required init(source _: Observable<StateType>, emitter _: ActionEmitter, state _: StateType) { // We know that the identifier is not empty. let shortcutSuiteName = Bundle.main.bundleIdentifier! + ".menuitems" self.shortcutsUserDefaults = UserDefaults(suiteName: shortcutSuiteName) self.shortcutsDefaultsController = NSUserDefaultsController( defaults: self.shortcutsUserDefaults, initialValues: nil ) super.init(frame: .zero) if let version = self.shortcutsUserDefaults?.integer(forKey: defaultsVersionKey), version > defaultsVersion { let alert = NSAlert() alert.alertStyle = .warning alert.messageText = "Incompatible Defaults for Shortcuts" alert.informativeText = "The stored defaults for shortcuts are not compatible with " + "this version of VimR. You can delete the stored defaults " + "by executing 'defaults delete com.qvacua.VimR.menuitems' " + "in Terminal." alert.runModal() return } self.migrateDefaults() self.initShortcutUserDefaults() self.addViews() self.initShortcutItems() if let children = self.shortcutItemsRoot.children { self.content.append(contentsOf: children) } self.initMenuItemsBindings() self.initOutlineViewBindings() self.shortcutList.expandItem(nil, expandChildren: true) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private let shortcutList = NSOutlineView.standardOutlineView() private let shortcutScrollView = NSScrollView.standardScrollView() private let resetButton = NSButton(forAutoLayout: ()) private let treeController = NSTreeController() private let shortcutItemsRoot = ShortcutItem(title: "root", isLeaf: false, item: nil) private let keyEqTransformer = DataToKeyEquivalentTransformer() private let keyEqModTransformer = DataToKeyEquivalentModifierMaskTransformer() private let shortcutsUserDefaults: UserDefaults? private let shortcutsDefaultsController: NSUserDefaultsController private func migrateDefaults() { if (self.shortcutsUserDefaults?.integer(forKey: defaultsVersionKey) ?? 0) == defaultsVersion { return } legacyDefaultShortcuts.forEach { id in let shortcut: Shortcut? if let dict = self.shortcutsUserDefaults?.value(forKey: id) as? [String: Any] { shortcut = Shortcut(dictionary: dict) } else { shortcut = defaultShortcuts[id] ?? nil } let data = ShortcutValueTransformer.shared.reverseTransformedValue(shortcut) as? NSData self.shortcutsUserDefaults?.set(data, forKey: id) } self.shortcutsUserDefaults?.set(defaultsVersion, forKey: defaultsVersionKey) } private func initShortcutUserDefaults() { let transformer = ShortcutValueTransformer.shared defaultShortcuts.forEach { id, shortcut in if self.shortcutsUserDefaults?.value(forKey: id) == nil { let shortcutData = transformer.reverseTransformedValue(shortcut) as? NSData self.shortcutsUserDefaults?.set(shortcutData, forKey: id) } } self.shortcutsUserDefaults?.set(defaultsVersion, forKey: defaultsVersionKey) } private func initOutlineViewBindings() { self.treeController.childrenKeyPath = "children" self.treeController.leafKeyPath = "isLeaf" self.treeController.countKeyPath = "childrenCount" self.treeController.objectClass = ShortcutItem.self self.treeController.avoidsEmptySelection = false self.treeController.preservesSelection = true self.treeController.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)] self.treeController.bind(.contentArray, to: self, withKeyPath: "content") self.shortcutList.bind(.content, to: self.treeController, withKeyPath: "arrangedObjects") self.shortcutList.bind( .selectionIndexPaths, to: self.treeController, withKeyPath: "selectionIndexPaths" ) } private func traverseMenuItems(with fn: (String, NSMenuItem) -> Void) { var queue = self.shortcutItemsRoot.children ?? [] while !queue.isEmpty { guard let item = queue.popLast() else { break } if item.isContainer, let children = item.children { queue.append(contentsOf: children) continue } guard let menuItem = item.item, let identifier = item.identifier, item.isLeaf else { continue } fn(identifier, menuItem) } } private func initMenuItemsBindings() { self.traverseMenuItems { identifier, menuItem in menuItem.bind( NSBindingName("keyEquivalent"), to: self.shortcutsDefaultsController, withKeyPath: "values.\(identifier)", options: [.valueTransformer: self.keyEqTransformer] ) menuItem.bind( NSBindingName("keyEquivalentModifierMask"), to: self.shortcutsDefaultsController, withKeyPath: "values.\(identifier)", options: [.valueTransformer: self.keyEqModTransformer] ) } } private func initShortcutItems() { guard let mainMenu = NSApplication.shared.mainMenu else { return } let firstLevel = mainMenu.items .suffix(from: 1) .filter { $0.identifier != debugMenuItemIdentifier } var queue = firstLevel.map { ( parent: self.shortcutItemsRoot, shortcutItem: ShortcutItem(title: $0.title, isLeaf: false, item: $0) ) } while !queue.isEmpty { guard let entry = queue.popLast() else { break } if !entry.shortcutItem.isLeaf || entry.shortcutItem.identifier?.hasPrefix("com.qvacua.vimr.menuitems.") == true { entry.parent.children?.append(entry.shortcutItem) } if entry.shortcutItem.isContainer, let childMenuItems = entry.shortcutItem.item?.submenu?.items { let shortcutChildItems = childMenuItems .filter { !$0.title.isEmpty } .map { menuItem in ( parent: entry.shortcutItem, shortcutItem: ShortcutItem( title: menuItem.title, isLeaf: !menuItem.hasSubmenu, item: menuItem ) ) } queue.append(contentsOf: shortcutChildItems) } } } private func updateShortcutService() { let transformer = ShortcutValueTransformer.shared let shortcuts = defaultShortcuts.compactMap { id, shortcut -> Shortcut? in if self.shortcutsUserDefaults?.value(forKey: id) == nil { return shortcut } return transformer.transformedValue( self.shortcutsUserDefaults?.value(forKey: id) ) as? Shortcut } self.shortcutService?.update(shortcuts: shortcuts) } private func addViews() { let paneTitle = self.paneTitleTextField(title: "Shortcuts") let shortcutList = self.shortcutList shortcutList.delegate = self let shortcutScrollView = self.shortcutScrollView shortcutScrollView.documentView = shortcutList let reset = self.resetButton reset.title = "Reset All to Default" reset.bezelStyle = .rounded reset.isBordered = true reset.setButtonType(.momentaryPushIn) reset.target = self reset.action = #selector(ShortcutsPref.resetToDefault) self.addSubview(paneTitle) self.addSubview(shortcutScrollView) self.addSubview(reset) paneTitle.autoPinEdge(toSuperviewEdge: .top, withInset: 18) paneTitle.autoPinEdge(toSuperviewEdge: .left, withInset: 18) paneTitle.autoPinEdge(toSuperviewEdge: .right, withInset: 18, relation: .greaterThanOrEqual) shortcutScrollView.autoPinEdge(.top, to: .bottom, of: paneTitle, withOffset: 18) shortcutScrollView.autoPinEdge(.left, to: .left, of: paneTitle) shortcutScrollView.autoPinEdge(toSuperviewEdge: .right, withInset: 18) reset.autoPinEdge(.left, to: .left, of: paneTitle) reset.autoPinEdge(.top, to: .bottom, of: shortcutScrollView, withOffset: 18) reset.autoPinEdge(toSuperviewEdge: .bottom, withInset: 18) } } // MARK: - Actions extension ShortcutsPref { @objc func resetToDefault(_: NSButton) { guard let window = self.window else { return } let alert = NSAlert() alert.addButton(withTitle: "Cancel") alert.addButton(withTitle: "Reset") alert.messageText = "Do you want to reset all shortcuts to their default values?" alert.alertStyle = .warning alert.beginSheetModal(for: window, completionHandler: { response in guard response == .alertSecondButtonReturn else { return } self.traverseMenuItems { identifier, _ in let shortcut = defaultShortcuts[identifier] ?? Shortcut(keyEquivalent: "") let valueToWrite = ShortcutValueTransformer.shared.reverseTransformedValue(shortcut) self.shortcutsDefaultsController.setValue(valueToWrite, forKeyPath: "values.\(identifier)") self.updateShortcutService() self.treeController.rearrangeObjects() } }) } } // MARK: - NSOutlineViewDelegate extension ShortcutsPref { func outlineView(_: NSOutlineView, rowViewForItem _: Any) -> NSTableRowView? { let view = self.shortcutList.makeView( withIdentifier: NSUserInterfaceItemIdentifier("shortcut-row-view"), owner: self ) as? ShortcutTableRow ?? ShortcutTableRow(withIdentifier: "shortcut-row-view") return view } func outlineView(_: NSOutlineView, viewFor _: NSTableColumn?, item: Any) -> NSView? { let cellView = self.shortcutList.makeView( withIdentifier: NSUserInterfaceItemIdentifier("shortcut-cell-view"), owner: self ) as? ShortcutTableCell ?? ShortcutTableCell(withIdentifier: "shortcut-cell-view") let repObj = (item as? NSTreeNode)?.representedObject guard let item = repObj as? ShortcutItem else { return nil } guard let identifier = item.identifier else { return cellView } cellView.isDir = !item.isLeaf cellView.text = item.title if item.isContainer { cellView.customized = false cellView.layoutViews() return cellView } cellView.customized = !self.areShortcutsEqual(identifier) cellView.layoutViews() cellView.setDelegateOfRecorder(self) cellView.bindRecorder(toKeyPath: "values.\(identifier)", to: self.shortcutsDefaultsController) return cellView } func outlineView(_: NSOutlineView, heightOfRowByItem _: Any) -> CGFloat { 28 } private func areShortcutsEqual(_ identifier: String) -> Bool { guard let dataFromDefaults = self.shortcutsDefaultsController.value( forKeyPath: "values.\(identifier)" ) as? NSData else { return true } guard let shortcutFromDefaults = ShortcutValueTransformer.shared .transformedValue(dataFromDefaults) as? Shortcut else { return true } let defaultShortcut = defaultShortcuts[identifier] ?? nil return shortcutFromDefaults.isEqual(to: defaultShortcut) == true } } // MARK: - SRRecorderControlDelegate extension ShortcutsPref { func recorderControlDidEndRecording(_: RecorderControl) { self.updateShortcutService() self.treeController.rearrangeObjects() } } private let defaultsVersionKey = "version" private let defaultsVersion = 337 private class DataToKeyEquivalentTransformer: ValueTransformer { override func transformedValue(_ value: Any?) -> Any? { guard let shortcut = ShortcutValueTransformer.shared.transformedValue(value) as? Shortcut else { return "" } return KeyEquivalentTransformer.shared.transformedValue(shortcut) } } private class DataToKeyEquivalentModifierMaskTransformer: ValueTransformer { override func transformedValue(_ value: Any?) -> Any? { guard let shortcut = ShortcutValueTransformer.shared .transformedValue(value) as? Shortcut else { return NSNumber(value: 0) } return KeyEquivalentModifierMaskTransformer.shared.transformedValue(shortcut) } }
mit
f07a74d399994fb22d5839636d8237fe
32.963542
100
0.710397
4.723651
false
false
false
false
tardieu/swift
test/Constraints/protocols.swift
12
11492
// RUN: %target-typecheck-verify-swift protocol Fooable { func foo() } protocol Barable { func bar() } extension Int : Fooable, Barable { func foo() {} func bar() {} } extension Float32 : Barable { func bar() {} } func f0(_: Barable) {} func f1(_ x: Fooable & Barable) {} func f2(_: Float) {} let nilFunc: Optional<(Barable) -> ()> = nil func g(_: (Barable & Fooable) -> ()) {} protocol Classable : AnyObject {} class SomeArbitraryClass {} func fc0(_: Classable) {} func fc1(_: Fooable & Classable) {} func fc2(_: AnyObject) {} func fc3(_: SomeArbitraryClass) {} func gc(_: (Classable & Fooable) -> ()) {} var i : Int var f : Float var b : Barable //===----------------------------------------------------------------------===// // Conversion to and among existential types //===----------------------------------------------------------------------===// f0(i) f0(f) f0(b) f1(i) f1(f) // expected-error{{argument type 'Float' does not conform to expected type 'Barable & Fooable'}} f1(b) // expected-error{{argument type 'Barable' does not conform to expected type 'Barable & Fooable'}} //===----------------------------------------------------------------------===// // Subtyping //===----------------------------------------------------------------------===// g(f0) // okay (subtype) g(f1) // okay (exact match) g(f2) // expected-error{{cannot convert value of type '(Float) -> ()' to expected argument type '(Barable & Fooable) -> ()'}} // FIXME: Workaround for ?? not playing nice with function types. infix operator ??* func ??*<T>(lhs: T?, rhs: T) -> T { return lhs ?? rhs } g(nilFunc ??* f0) gc(fc0) // okay gc(fc1) // okay gc(fc2) // okay gc(fc3) // expected-error{{cannot convert value of type '(SomeArbitraryClass) -> ()' to expected argument type '(Classable & Fooable) -> ()'}} // rdar://problem/19600325 func getAnyObject() -> AnyObject? { return SomeArbitraryClass() } func castToClass(_ object: Any) -> SomeArbitraryClass? { return object as? SomeArbitraryClass } _ = getAnyObject().map(castToClass) _ = { (_: Any) -> Void in return } as ((Int) -> Void) let _: (Int) -> Void = { (_: Any) -> Void in return } let _: () -> Any = { () -> Int in return 0 } let _: () -> Int = { () -> String in // expected-error {{declared closure result 'String' is incompatible with contextual type 'Int'}} return "" } //===----------------------------------------------------------------------===// // Members of archetypes //===----------------------------------------------------------------------===// func id<T>(_ t: T) -> T { return t } protocol Initable { init() } protocol P : Initable { func bar(_ x: Int) mutating func mut(_ x: Int) static func tum() } protocol ClassP : class { func bas(_ x: Int) func quux(_ x: Int) } class ClassC : ClassP { func bas(_ x: Int) {} } extension ClassP { func quux(_ x: Int) {} func bing(_ x: Int) {} } func generic<T: P>(_ t: T) { var t = t // Instance member of archetype let _: (Int) -> () = id(t.bar) let _: () = id(t.bar(0)) // Static member of archetype metatype let _: () -> () = id(T.tum) // Instance member of archetype metatype let _: (T) -> (Int) -> () = id(T.bar) let _: (Int) -> () = id(T.bar(t)) _ = t.mut // expected-error{{partial application of 'mutating' method is not allowed}} _ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}} } func genericClassP<T: ClassP>(_ t: T) { // Instance member of archetype) let _: (Int) -> () = id(t.bas) let _: () = id(t.bas(0)) // Instance member of archetype metatype) let _: (T) -> (Int) -> () = id(T.bas) let _: (Int) -> () = id(T.bas(t)) let _: () = id(T.bas(t)(1)) } func genericClassC<C : ClassC>(_ c: C) { // Make sure that we can find members of protocol extensions // on a class-bound archetype let _ = c.bas(123) let _ = c.quux(123) let _ = c.bing(123) } //===----------------------------------------------------------------------===// // Members of existentials //===----------------------------------------------------------------------===// func existential(_ p: P) { var p = p // Fully applied mutating method p.mut(1) _ = p.mut // expected-error{{partial application of 'mutating' method is not allowed}} // Instance member of existential) let _: (Int) -> () = id(p.bar) let _: () = id(p.bar(0)) // Static member of existential metatype) let _: () -> () = id(type(of: p).tum) } func staticExistential(_ p: P.Type, pp: P.Protocol) { let _ = p() // expected-error{{initializing from a metatype value must reference 'init' explicitly}} let _ = p().bar // expected-error{{initializing from a metatype value must reference 'init' explicitly}} let _ = p().bar(1) // expected-error{{initializing from a metatype value must reference 'init' explicitly}} let ppp: P = p.init() _ = pp() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}} // expected-error{{initializing from a metatype value must reference 'init' explicitly}} _ = pp().bar // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}} // expected-error{{initializing from a metatype value must reference 'init' explicitly}} _ = pp().bar(2) // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}} // expected-error{{initializing from a metatype value must reference 'init' explicitly}} _ = pp.init() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}} _ = pp.init().bar // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}} _ = pp.init().bar(3) // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}} _ = P() // expected-error{{protocol type 'P' cannot be instantiated}} _ = P().bar // expected-error{{protocol type 'P' cannot be instantiated}} _ = P().bar(4) // expected-error{{protocol type 'P' cannot be instantiated}} // Instance member of metatype let _: (P) -> (Int) -> () = P.bar let _: (Int) -> () = P.bar(ppp) P.bar(ppp)(5) // Instance member of metatype value let _: (P) -> (Int) -> () = pp.bar let _: (Int) -> () = pp.bar(ppp) pp.bar(ppp)(5) // Static member of existential metatype value let _: () -> () = p.tum // Instance member of existential metatype -- not allowed _ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}} _ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}} // Static member of metatype -- not allowed _ = pp.tum // expected-error{{static member 'tum' cannot be used on protocol metatype 'P.Protocol'}} _ = P.tum // expected-error{{static member 'tum' cannot be used on protocol metatype 'P.Protocol'}} } protocol StaticP { static func foo(a: Int) } extension StaticP { func bar() { _ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype 'StaticP.Protocol'}} {{9-16=Self}} func nested() { _ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype 'StaticP.Protocol'}} {{11-18=Self}} } } } func existentialClassP(_ p: ClassP) { // Instance member of existential) let _: (Int) -> () = id(p.bas) let _: () = id(p.bas(0)) // Instance member of existential metatype) let _: (ClassP) -> (Int) -> () = id(ClassP.bas) let _: (Int) -> () = id(ClassP.bas(p)) let _: () = id(ClassP.bas(p)(1)) } // Partial application of curried protocol methods protocol Scalar {} protocol Vector { func scale(_ c: Scalar) -> Self } protocol Functional { func apply(_ v: Vector) -> Scalar } protocol Coalgebra { func coproduct(_ f: Functional) -> (_ v1: Vector, _ v2: Vector) -> Scalar } // Make sure existential is closed early when we partially apply func wrap<T>(_ t: T) -> T { return t } func exercise(_ c: Coalgebra, f: Functional, v: Vector) { let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f)) let _: (Scalar) -> Vector = v.scale } // Make sure existential isn't closed too late protocol Copyable { func copy() -> Self } func copyTwice(_ c: Copyable) -> Copyable { return c.copy().copy() } //===----------------------------------------------------------------------===// // Dynamic self //===----------------------------------------------------------------------===// protocol Clonable { func maybeClone() -> Self? func doubleMaybeClone() -> Self?? func subdivideClone() -> (Self, Self) func metatypeOfClone() -> Self.Type func goodClonerFn() -> (() -> Self) } extension Clonable { func badClonerFn() -> ((Self) -> Self) { } func veryBadClonerFn() -> ((inout Self) -> ()) { } func extClone() -> Self { } func extMaybeClone(_ b: Bool) -> Self? { } func extProbablyClone(_ b: Bool) -> Self! { } static func returnSelfStatic() -> Self { } static func returnSelfOptionalStatic(_ b: Bool) -> Self? { } static func returnSelfIUOStatic(_ b: Bool) -> Self! { } } func testClonableArchetype<T : Clonable>(_ t: T) { // Instance member of extension returning Self) let _: (T) -> () -> T = id(T.extClone) let _: () -> T = id(T.extClone(t)) let _: T = id(T.extClone(t)()) let _: () -> T = id(t.extClone) let _: T = id(t.extClone()) let _: (T) -> (Bool) -> T? = id(T.extMaybeClone) let _: (Bool) -> T? = id(T.extMaybeClone(t)) let _: T? = id(T.extMaybeClone(t)(false)) let _: (Bool) -> T? = id(t.extMaybeClone) let _: T? = id(t.extMaybeClone(true)) let _: (T) -> (Bool) -> T! = id(T.extProbablyClone) let _: (Bool) -> T! = id(T.extProbablyClone(t)) let _: T! = id(T.extProbablyClone(t)(true)) let _: (Bool) -> T! = id(t.extProbablyClone) let _: T! = id(t.extProbablyClone(true)) // Static member of extension returning Self) let _: () -> T = id(T.returnSelfStatic) let _: T = id(T.returnSelfStatic()) let _: (Bool) -> T? = id(T.returnSelfOptionalStatic) let _: T? = id(T.returnSelfOptionalStatic(false)) let _: (Bool) -> T! = id(T.returnSelfIUOStatic) let _: T! = id(T.returnSelfIUOStatic(true)) } func testClonableExistential(_ v: Clonable, _ vv: Clonable.Type) { let _: Clonable? = v.maybeClone() let _: Clonable?? = v.doubleMaybeClone() // FIXME: Tuple-to-tuple conversions are not implemented let _: (Clonable, Clonable) = v.subdivideClone() // expected-error@-1{{cannot express tuple conversion '(Clonable, Clonable)' to '(Clonable, Clonable)'}} let _: Clonable.Type = v.metatypeOfClone() let _: () -> Clonable = v.goodClonerFn() // Instance member of extension returning Self let _: () -> Clonable = id(v.extClone) let _: Clonable = id(v.extClone()) let _: Clonable? = id(v.extMaybeClone(true)) let _: Clonable! = id(v.extProbablyClone(true)) // Static member of extension returning Self) let _: () -> Clonable = id(vv.returnSelfStatic) let _: Clonable = id(vv.returnSelfStatic()) let _: (Bool) -> Clonable? = id(vv.returnSelfOptionalStatic) let _: Clonable? = id(vv.returnSelfOptionalStatic(false)) let _: (Bool) -> Clonable! = id(vv.returnSelfIUOStatic) let _: Clonable! = id(vv.returnSelfIUOStatic(true)) let _ = v.badClonerFn() // expected-error {{member 'badClonerFn' cannot be used on value of protocol type 'Clonable'; use a generic constraint instead}} let _ = v.veryBadClonerFn() // expected-error {{member 'veryBadClonerFn' cannot be used on value of protocol type 'Clonable'; use a generic constraint instead}} }
apache-2.0
a6c05fbe02b3f70ff30a29343677efa2
30.313351
195
0.585712
3.644783
false
false
false
false
davejlin/treehouse
swift/swift2/restaurant-finder/RestaurantFinder/FoursquareModels.swift
1
2283
// // FoursquareModels.swift // RestaurantFinder // // Created by Lin David, US-205 on 10/9/16. // Copyright © 2016 Treehouse. All rights reserved. // import Foundation struct Coordinate { let latitude: Double let longitude: Double } extension Coordinate: CustomStringConvertible { var description: String { return "\(latitude),\(longitude)" } } struct Location { let coordinate: Coordinate? let distance: Double? let countryCode: String? let country: String? let state: String? let city: String? let streetAddress: String? let crossStreet: String? let postalCode: String? } extension Location: JSONDecodable { init?(json: JSON) { if let lat = json["lat"] as? Double, lon = json["lng"] as? Double { coordinate = Coordinate(latitude: lat, longitude: lon) } else { coordinate = nil } distance = json["distance"] as? Double countryCode = json["cc"] as? String country = json["country"] as? String state = json["state"] as? String city = json["city"] as? String streetAddress = json["address"] as? String crossStreet = json["crossStreet"] as? String postalCode = json["postalCode"] as? String } } struct Venue { let id: String let name: String let location: Location? let categoryName: String let checkins: Int } extension Venue: JSONDecodable { init?(json: JSON) { guard let id = json["id"] as? String, name = json["name"] as? String else { return nil } guard let categories = json["categories"] as? [JSON], let category = categories.first, let categoryName = category["shortName"] as? String else { return nil } guard let stats = json["stats"] as? JSON, let checkinsCount = stats["checkinsCount"] as? Int else { return nil } self.id = id self.name = name self.categoryName = categoryName self.checkins = checkinsCount if let locationDict = json["location"] as? JSON { self.location = Location(json: locationDict) } else { self.location = nil } } }
unlicense
da7c8b225aead2550a588a746ba876dd
25.241379
153
0.588081
4.405405
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0054.xcplaygroundpage/Contents.swift
1
8744
/*: # Abolish `ImplicitlyUnwrappedOptional` type * Proposal: [SE-0054](0054-abolish-iuo.md) * Author: [Chris Willmore](http://github.com/cwillmor) * Review Manager: [Chris Lattner](https://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-March/000084.html) * Implementation: [apple/swift#2322](https://github.com/apple/swift/pull/2322) ## Introduction This proposal seeks to remove the `ImplicitlyUnwrappedOptional` type from the Swift type system and replace it with an IUO attribute on declarations. Appending `!` to the type of a Swift declaration will give it optional type and annotate the declaration with an attribute stating that it may be implicitly unwrapped when used. Swift-evolution thread: ["Abolish IUO Type"](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160314/012752.html) ## Motivation The `ImplicitlyUnwrappedOptional` ("IUO") type is a valuable tool for importing Objective-C APIs where the nullability of a parameter or return type is unspecified. It also represents a convenient mechanism for working through definite initialization problems in initializers. However, IUOs are a transitional technology; they represent an easy way to work around un-annotated APIs, or the lack of language features that could more elegantly handle certain patterns of code. As such, we would like to limit their usage moving forward, and introduce more specific language features to take their place. Except for a few specific scenarios, optionals are always the safer bet, and we’d like to encourage people to use them instead of IUOs. This proposal seeks to limit the adoption of IUOs to places where they are actually required, and put the Swift language on the path to removing implicitly unwrapped optionals from the system entirely when other technologies render them unnecessary. It also completely abolishes any notion of IUOs below the type-checker level of the compiler, which will substantially simplify the compiler implementation. ## Proposed solution In this proposal, we continue to use the syntax `T!` for declaring implicitly unwrapped optional values in the following locations: * property and variable declarations * initializer declarations * function and method declarations * subscript declarations * parameter declarations (with the exception of vararg parameters) However, the appearance of `!` at the end of a property or variable declaration's type no longer indicates that the declaration has IUO type; rather, it indicates that (1) the declaration has optional type, and (2) the declaration has an attribute indicating that its value may be implicitly forced. (No human would ever write or observe this attribute, but we will refer to it as `@_autounwrapped`.) Such a declaration is referred to henceforth as an IUO declaration. Likewise, the appearance of `!` at the end of the return type of a function indicates that the function has optional return type and its return value may be implicitly unwrapped. The use of `init!` in an initializer declaration indicates that the initializer is failable and the result of the initializer may be implicitly unwrapped. In both of these cases, the `@_autounwrapped` attribute is attached to the declaration. A reference to an IUO variable or property prefers to bind to an optional, but may be implicitly forced (i.e. converted to the underlying type) when being type-checked; this replicates the current behavior of a declaration with IUO type. Likewise, the result of a function application or initialization where the callee is a reference to an IUO function declaration prefers to retain its optional type, but may be implicitly forced if necessary. If the expression can be explicitly type checked with a strong optional type, it will be. However, the type checker will fall back to forcing the optional if necessary. The effect of this behavior is that the result of any expression that refers to a value declared as `T!` will either have type `T` or type `T?`. For example, in the following code: ```Swift let x: Int! = 5 let y = x let z = x + 0 ``` … `x` is declared as an IUO, but because the initializer for `y` type checks correctly as an optional, `y` will be bound as type `Int?`. However, the initializer for `z` does not type check with `x` declared as an optional (there's no overload of `+` that takes an optional), so the compiler forces the optional and type checks the initializer as `Int`. This model is more predictable because it prevents IUOs from propagating implicitly through the codebase, and converts them to strong optionals, the safer option, by default. An IUO variable may still be converted to a value with non-optional type, through either evaluating it in a context which requires the non-optional type, explicitly converting it to a non-optional type using the `as` operator, binding it to a variable with explicit optional type, or using the force operator (`!`). Because IUOs are an attribute on declarations rather than on types, the `ImplicitlyUnwrappedOptional` type, as well as the long form `ImplicitlyUnwrappedOptional<T>` syntax, is removed. Types with nested IUOs are no longer allowed. This includes types such as `[Int!]` and `(Int!, Int!)`. Type aliases may not have IUO information associated with them. Thus the statement `typealias X = Int!` is illegal. This includes type aliases resulting from imported `typedef` statements. For example, the Objective-C type declaration ```Objective-C typedef void (^ViewHandler)(NSView *); ``` ... is imported as the Swift type declaration ```Swift typealias ViewHandler = (NSView?) -> () ``` Note that the parameter type is `NSView?`, not `NSView!`. ## Examples ```Swift func f() -> Int! { return 3 } // f: () -> Int?, has IUO attribute let x1 = f() // succeeds; x1: Int? = 3 let x2: Int? = f() // succeeds; x2: Int? = .some(3) let x3: Int! = f() // succeeds; x3: Int? = .some(3), has IUO attribute let x4: Int = f() // succeeds; x4: Int = 3 let a1 = [f()] // succeeds; a: [Int?] = [.some(3)] let a2: [Int!] = [f()] // illegal, nested IUO type let a3: [Int] = [f()] // succeeds; a: [Int] = [3] func g() -> Int! { return nil } // f: () -> Int?, has IUO attribute let y1 = g() // succeeds; y1: Int? = .none let y2: Int? = g() // succeeds; y2: Int? = .none let y3: Int! = g() // succeeds; y3: Int? = .none, has IUO attribute let y4: Int = g() // traps let b1 = [g()] // succeeds; b: [Int?] = [.none] let b2: [Int!] = [g()] // illegal, nested IUO type let b3: [Int] = [g()] // traps func p<T>(x: T) { print(x) } p(f()) // prints "Optional(3)"; p is instantiated with T = Int? if let x5 = f() { // executes, with x5: Int = 3 } if let y5 = g() { // does not execute } ``` ## Impact on existing code These changes will break existing code; as a result, I would like for them to be considered for inclusion in Swift 3. This breakage will come in two forms: * Variable bindings which previously had inferred type `T!` from their binding on the right-hand side will now have type `T?`. The compiler will emit an error at sites where those bound variables are used in a context that demands a non-optional type and suggest that the value be forced with the `!` operator. * Explicitly written nested IUO types (like `[Int!]`) will have to be rewritten to use the corresponding optional type (`[Int?]`) or non-optional type (`[Int]`) depending on what's more appropriate for the context. However, most declarations with non-nested IUO type will continue to work as they did before. * Unsugared use of the `ImplicitlyUnwrappedOptional` type will have to be replaced with the postfix `!` notation. It will still be possible to declare IUO properties, so the following deferred initialization pattern will still be possible: ```Swift struct S { var x: Int! init() {} func initLater(x someX: Int) { x = someX } } ``` I consider the level of breakage resulting from this change acceptable. Types imported from Objective-C APIs change frequently as those APIs gain nullability annotations, and that occasionally breaks existing code too; this change will have similar effect. ## Alternatives considered * Continue to allow IUO type, but don't propagate it to variables and intermediate values without explicit type annotation. This resolves the issue of IUO propagation but still allows nested IUO types, and doesn't address the complexity of handling IUOs below the Sema level of the compiler. * Remove IUOs completely. Untenable due to the prevalence of deferred initialization and unannotated Objective-C API in today's Swift ecosystem. ---------- [Previous](@previous) | [Next](@next) */
mit
775450342b661a121c8435f314932e72
41.42233
128
0.750429
4.05334
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Classtable/Controller/ClasstableViewController.swift
1
18035
// // ClasstableViewController.swift // WePeiYang // // Created by Qin Yubo on 16/1/28. // Copyright © 2016年 Qin Yubo. All rights reserved. // import UIKit import SnapKit import STPopup import DateTools import ObjectMapper import SwiftyJSON let CLASSTABLE_CACHE_KEY = "CLASSTABLE_CACHE" let CLASSTABLE_COLOR_CONFIG_KEY = "CLASSTABLE_COLOR_CONFIG" let CLASSTABLE_TERM_START_KEY = "CLASSTABLE_TERM_START" let colorArr = [UIColor.flatRedColor(), UIColor.flatOrangeColor(), UIColor.flatMagentaColor(), UIColor.flatGreenColor(), UIColor.flatSkyBlueColor(), UIColor.flatMintColor(), UIColor.flatTealColor(), UIColor.flatPinkColorDark(), UIColor.flatBlueColor(), UIColor.flatLimeColor(), UIColor.flatPurpleColor(), UIColor.flatYellowColorDark(), UIColor.flatWatermelonColorDark(), UIColor.flatCoffeeColor()] class ClasstableViewController: UIViewController, ClassCellViewDelegate { @IBOutlet weak var classTableScrollView: UIScrollView! var dataArr: [ClassData] = [] var detailController: STPopupController! var currentWeek = 0 var classCellsNotAround: [ClassCellView] = [] var classCellsAround: [ClassCellView] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.edgesForExtendedLayout = .None let refreshBtn = UIBarButtonItem().bk_initWithBarButtonSystemItem(.Refresh, handler: {sender in self.refresh() }) as! UIBarButtonItem self.navigationItem.rightBarButtonItem = refreshBtn self.title = "课程表" self.dataArr = [] self.currentWeek = 0 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ClasstableViewController.refreshNotificationReceived), name: NOTIFICATION_LOGIN_SUCCESSED, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ClasstableViewController.refreshNotificationReceived), name: NOTIFICATION_BINDTJU_SUCCESSED, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ClasstableViewController.backNotificationReceived), name: NOTIFICATION_LOGIN_CANCELLED, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ClasstableViewController.backNotificationReceived), name: NOTIFICATION_BINDTJU_CANCELLED, object: nil) self.loadClassTable() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.tintColor = UIColor(red: 1.0, green: 152/255.0, blue: 0, alpha: 1.0) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { self.updateView(size) } override func viewDidLayoutSubviews() { updateViewWithClassesNotAround(UIScreen.mainScreen().bounds.size) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - Private Methods private func updateViewWithClassesNotAround(size: CGSize) { let classSize = self.classCellSizeWithScreenSize(size) guard !classCellsNotAround.isEmpty else { return } /*for classCellNotAround in classCellsNotAround { var fooArr: [ClassCellView] = [] for classCellAround in classCellsAround { for arrangeNotAround in (classCellNotAround.classData?.arrange)! { for arrangeAround in (classCellAround.classData?.arrange)! { if !(arrangeAround.day == arrangeNotAround.day && arrangeAround.start == arrangeNotAround.start) { classTableScrollView.addSubview(classCellNotAround) classCellNotAround.snp_makeConstraints { make in make.width.equalTo(classSize.width) make.height.equalTo(CGFloat(arrangeNotAround.end - arrangeNotAround.start + 1) * classSize.height) make.left.equalTo(CGFloat(arrangeNotAround.day) * classSize.width) make.top.equalTo(CGFloat(arrangeNotAround.start - 1) * classSize.height) } } } } } }*/ /*for i in 0..<classCellsNotAround.count { for j in 0..<classCellsAround.count { for l in 0..<classCellsNotAround[i].classData!.arrange.count { for m in 0..<classCellsAround[j].classData!.arrange.count { let arrangeAround = classCellsAround[j].classData!.arrange[m] let arrangeNotAround = classCellsNotAround[i].classData!.arrange[l] if !(arrangeAround.day == arrangeNotAround.day && arrangeAround.start == arrangeNotAround.start) { classTableScrollView.addSubview(classCellsNotAround[i]) classCellsNotAround[i].snp_makeConstraints { make in make.width.equalTo(classSize.width) make.height.equalTo(CGFloat(arrangeNotAround.end - arrangeNotAround.start + 1) * classSize.height) make.left.equalTo(CGFloat(arrangeNotAround.day) * classSize.width) make.top.equalTo(CGFloat(arrangeNotAround.start - 1) * classSize.height) } } } } } }*/ } private func loadClassTable() { if AccountManager.tokenExists() { wpyCacheManager.loadGroupCacheDataWithKey(CLASSTABLE_TERM_START_KEY, andBlock: {termStart in if termStart != nil { let startDate = NSDate(timeIntervalSince1970: Double(termStart as! Int)) //log.obj(startDate)/ self.currentWeek = NSDate().weeksFrom(startDate) + 1 self.title = "第 \(self.currentWeek) 周" } else { self.refresh() } }) wpyCacheManager.loadGroupCacheDataWithKey(CLASSTABLE_CACHE_KEY, andBlock: {data in if data != nil { self.dataArr = Mapper<ClassData>().mapArray(data)! self.updateView(UIScreen.mainScreen().bounds.size) } else { self.refresh() } }) } else { let loginVC = LoginViewController(nibName: "LoginViewController", bundle: nil) self.presentViewController(loginVC, animated: true, completion: nil) } } private func refresh() { MsgDisplay.showLoading() ClasstableDataManager.getClasstableData({(data, termStart) in MsgDisplay.dismiss() wpyCacheManager.removeCacheDataForKey(CLASSTABLE_COLOR_CONFIG_KEY) self.dataArr = Mapper<ClassData>().mapArray(data)! //log.any(JSON(data))/ self.updateView(self.view.bounds.size) wpyCacheManager.saveGroupCacheData(data, withKey: CLASSTABLE_CACHE_KEY) wpyCacheManager.saveGroupCacheData(termStart, withKey: CLASSTABLE_TERM_START_KEY) let startDate = NSDate(timeIntervalSince1970: Double(termStart)) self.currentWeek = NSDate().weeksFrom(startDate) + 1 self.title = "第 \(self.currentWeek) 周" }, notBinded: { MsgDisplay.dismiss() let bindTjuVC = BindTjuViewController(style: .Grouped) self.presentViewController(UINavigationController(rootViewController: bindTjuVC), animated: true, completion: nil) }, otherFailure: {errorMsg in MsgDisplay.showErrorMsg(errorMsg) }) } private func updateView(size: CGSize) { for view in classTableScrollView.subviews { view.removeFromSuperview() } let classSize = self.classCellSizeWithScreenSize(size) classTableScrollView.contentSize = self.contentSizeWithScreenSize(size) for i in 0...11 { let classNumberCell = ClassCellView() classNumberCell.classLabel.text = " \(i+1) " classNumberCell.classLabel.sizeToFit() classNumberCell.backgroundColor = UIColor.clearColor() classNumberCell.classLabel.textColor = UIColor.lightGrayColor() classNumberCell.classLabel.font = UIFont.systemFontOfSize(UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 16 : (size.width > 320) ? 12 : 10) classTableScrollView.addSubview(classNumberCell) classNumberCell.snp_makeConstraints(closure: { make in make.top.equalTo(CGFloat(i) * classSize.height) make.left.equalTo(0) //make.width.equalTo(classSize.width) make.height.equalTo(classSize.height) }) } var colorConfig = [String: UIColor]() wpyCacheManager.loadCacheDataWithKey(CLASSTABLE_COLOR_CONFIG_KEY, andBlock: {obj in colorConfig = obj as! [String: UIColor] }, failed: nil) var colorArray = colorArr for tmpClass in dataArr { var classBgColor: UIColor! if wpyCacheManager.cacheDataExistsWithKey(CLASSTABLE_COLOR_CONFIG_KEY) { //log.word("fuckin entered")/ if colorConfig[tmpClass.courseId] != nil { classBgColor = colorConfig[tmpClass.courseId] //log.any("fucking entered if \(classBgColor)")/ } else { classBgColor = UIColor.randomFlatColor() //log.any("fucking entered else \(classBgColor)")/ } } else { if colorArray.count <= 0 { colorArray = colorArr } classBgColor = colorArray.first colorConfig[tmpClass.courseId] = classBgColor colorArray.removeFirst() } for tmpArrange in tmpClass.arrange { let classCell = ClassCellView() classCell.classData = tmpClass classCell.classLabel.text = "\(tmpClass.courseName)@\(tmpArrange.room)" // 针对设备宽度控制字号 classCell.classLabel.font = UIFont.systemFontOfSize(UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 16 : (size.width > 320) ? 12 : 10) classCell.delegate = self classCell.alpha = 0.7 let gap: CGFloat = 2 classCell.layer.cornerRadius = gap+2 if Int(tmpClass.weekStart) <= currentWeek && Int(tmpClass.weekEnd) >= currentWeek { classCellsAround.append(classCell) classTableScrollView.addSubview(classCell) classCell.snp_makeConstraints { make in make.width.equalTo(classSize.width-gap) make.height.equalTo(CGFloat(tmpArrange.end - tmpArrange.start + 1) * classSize.height-gap) make.left.equalTo(CGFloat(tmpArrange.day-1) * classSize.width+22.5) make.top.equalTo(CGFloat(tmpArrange.start - 1) * classSize.height) } if (tmpArrange.week == "单双周") || (currentWeek % 2 == 0 && tmpArrange.week == "双周") || (currentWeek % 2 == 1 && tmpArrange.week == "单周") { classCell.backgroundColor = classBgColor } else { // classCell.alpha = 0.3 // classCell.backgroundColor = UIColor.flatGrayColor() // classCell.classLabel.textColor = UIColor.darkGrayColor() classCell.removeFromSuperview() } } else { classCell.classLabel.font = UIFont.systemFontOfSize(UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 16 : (size.width > 320) ? 12 : 10) classCell.delegate = self classCell.backgroundColor = .flatWhiteColor() classCell.classLabel.textColor = .flatGrayColorDark() classCellsNotAround.append(classCell) for foo in classTableScrollView.subviews { if foo.isKindOfClass(ClassCellView) { //log.any(foo.frame)/ } } } } /*for tmpArrange in tmpClass.arrange { let classCell = ClassCellView() classTableScrollView.addSubview(classCell) classCell.classData = tmpClass classCell.snp_makeConstraints(closure: { make in make.width.equalTo(classSize.width) make.height.equalTo(CGFloat(tmpArrange.end - tmpArrange.start + 1) * classSize.height) make.left.equalTo(CGFloat(tmpArrange.day) * classSize.width) make.top.equalTo(CGFloat(tmpArrange.start - 1) * classSize.height) }) classCell.classLabel.text = "\(tmpClass.courseName)@\(tmpArrange.room)" // 针对设备宽度控制字号 classCell.classLabel.font = UIFont.systemFontOfSize(UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 16 : (size.width > 320) ? 12 : 10) classCell.delegate = self // 考虑不在当前周数内的科目 if Int(tmpClass.weekStart) <= currentWeek && Int(tmpClass.weekEnd) >= currentWeek { // 单双周判断 // MARK: - WARNING 单双周可能有课不一样 if (tmpArrange.week == "单双周") || (currentWeek % 2 == 0 && tmpArrange.week == "双周") || (currentWeek % 2 == 1 && tmpArrange.week == "单周") { classCell.backgroundColor = classBgColor } else { // classCell.backgroundColor = UIColor.flatWhiteColor() // classCell.classLabel.textColor = UIColor.flatGrayColorDark() classCell.removeFromSuperview() } } else { classCell.backgroundColor = UIColor.flatWhiteColor() classCell.classLabel.textColor = UIColor.flatGrayColorDark() } }*/ } wpyCacheManager.saveCacheData(colorConfig, withKey: CLASSTABLE_COLOR_CONFIG_KEY) } private func classCellSizeWithScreenSize(screenSize: CGSize) -> CGSize { let width = (screenSize.width - 22.5)/7 // 高度的参数需要针对不同设备进行不同的控制,甚至对不同屏幕方向也要有所适配 var height: CGFloat = 0 if screenSize.width <= 320 { height = width * 1.4 } else if screenSize.width <= 414 { height = width * 1.1 } else if screenSize.width <= 768 { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { height = width * 0.35 } else { height = width * 0.7 } } else if screenSize.width <= 1024 { height = width * 0.5 } else { height = width * 0.3 } return CGSizeMake(width, height) } private func contentSizeWithScreenSize(screenSize: CGSize) -> CGSize { let cellSize = self.classCellSizeWithScreenSize(screenSize) let contentWidth = screenSize.width let contentHeight = cellSize.height * 12 return CGSizeMake(contentWidth, contentHeight) } // MARK: - Public Methods func refreshNotificationReceived() { self.refresh() } func backNotificationReceived() { self.navigationController?.popViewControllerAnimated(false) } func cellViewTouched(cellView: ClassCellView) { // print("\(cellView.classData!.courseName) : \(cellView.frame)") let classDetailController = ClassDetailViewController(nibName: "ClassDetailViewController", bundle: nil) classDetailController.classData = cellView.classData! classDetailController.classColor = cellView.backgroundColor detailController = STPopupController(rootViewController: classDetailController) let blurEffect = UIBlurEffect(style: .Dark) detailController.backgroundView = UIVisualEffectView(effect: blurEffect) detailController.backgroundView.addGestureRecognizer((UITapGestureRecognizer().bk_initWithHandler({(recognizer, state, point) in self.detailController.dismiss() }) as! UITapGestureRecognizer)) detailController.presentInViewController(self) } // MARK: - IBActions /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
2bc9bb6f64268e0e009f7d0ec5b6a094
45.416667
397
0.584661
5.012373
false
false
false
false
adamhartford/SwiftR
SwiftR/SwiftR.swift
1
20672
// // SwiftR.swift // SwiftR // // Created by Adam Hartford on 4/13/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import Foundation import WebKit @objc public enum ConnectionType: Int { case hub case persistent } @objc public enum State: Int { case connecting case connected case disconnected } public enum Transport { case auto case webSockets case foreverFrame case serverSentEvents case longPolling var stringValue: String { switch self { case .webSockets: return "webSockets" case .foreverFrame: return "foreverFrame" case .serverSentEvents: return "serverSentEvents" case .longPolling: return "longPolling" default: return "auto" } } } public enum SwiftRError: Error { case notConnected public var message: String { switch self { case .notConnected: return "Operation requires connection, but none available." } } } class SwiftR { static var connections = [SignalR]() #if os(iOS) public class func cleanup() { let temp = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("SwiftR", isDirectory: true) let fileManager = FileManager.default do { if fileManager.fileExists(atPath: temp.path) { try fileManager.removeItem(at: temp) } } catch { print("Failed to remove temp JavaScript: \(error)") } } #endif } open class SignalR: NSObject, SwiftRWebDelegate { static var connections = [SignalR]() var internalID: String! var ready = false public var signalRVersion: SignalRVersion = .v2_2_2 public var useWKWebView = false public var transport: Transport = .auto /// load Web resource from the provided url, which will be used as Origin HTTP header public var originUrlString: String? var webView: SwiftRWebView! var wkWebView: WKWebView! var baseUrl: String var connectionType: ConnectionType var readyHandler: ((SignalR) -> ())! var hubs = [String: Hub]() open var state: State = .disconnected open var connectionID: String? open var received: ((Any?) -> ())? open var starting: (() -> ())? open var connected: (() -> ())? open var disconnected: (() -> ())? open var connectionSlow: (() -> ())? open var connectionFailed: (() -> ())? open var reconnecting: (() -> ())? open var reconnected: (() -> ())? open var error: (([String: Any]?) -> ())? var jsQueue: [(String, ((Any?) -> ())?)] = [] open var customUserAgent: String? open var queryString: Any? { didSet { if let qs: Any = queryString { if let jsonData = try? JSONSerialization.data(withJSONObject: qs, options: JSONSerialization.WritingOptions()) { let json = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String runJavaScript("swiftR.connection.qs = \(json)") } } else { runJavaScript("swiftR.connection.qs = {}") } } } open var headers: [String: String]? { didSet { if let h = headers { if let jsonData = try? JSONSerialization.data(withJSONObject: h, options: JSONSerialization.WritingOptions()) { let json = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String runJavaScript("swiftR.headers = \(json)") } } else { runJavaScript("swiftR.headers = {}") } } } public init(_ baseUrl: String, connectionType: ConnectionType = .hub) { internalID = NSUUID().uuidString self.baseUrl = baseUrl self.connectionType = connectionType super.init() } public func connect(_ callback: (() -> ())? = nil) { readyHandler = { [weak self] _ in self?.jsQueue.forEach { self?.runJavaScript($0.0, callback: $0.1) } self?.jsQueue.removeAll() if let hubs = self?.hubs { hubs.forEach { $0.value.initialize() } } self?.ready = true callback?() } initialize() } private func initialize() { #if COCOAPODS let bundle = Bundle(identifier: "org.cocoapods.SwiftR")! #elseif SWIFTR_FRAMEWORK let bundle = Bundle(identifier: "com.adamhartford.SwiftR")! #else let bundle = Bundle.main #endif let jqueryURL = bundle.url(forResource: "jquery-2.1.3.min", withExtension: "js")! let signalRURL = bundle.url(forResource: "jquery.signalr-\(signalRVersion).min", withExtension: "js")! let jsURL = bundle.url(forResource: "SwiftR", withExtension: "js")! // script HTML snippet helpers let scriptAsSrc: (URL) -> String = { url in return "<script src='\(url.absoluteString)'></script>" } let scriptAsContent: (URL) -> String = { url in let scriptContent = try! String(contentsOf: url, encoding: .utf8) return "<script>\(scriptContent)</script>" } let script: (URL) -> String = { url in return self.originUrlString != nil ? scriptAsContent(url) : scriptAsSrc(url) } // build script sections var jqueryInclude = script(jqueryURL) var signalRInclude = script(signalRURL) var jsInclude = script(jsURL) /// use originUrlString if provided, otherwise fallback to bundle URL let baseHTMLUrl = originUrlString.map { URL(string: $0) } ?? bundle.bundleURL if useWKWebView { // Loading file:// URLs from NSTemporaryDirectory() works on iOS, not OS X. // Workaround on OS X is to include the script directly. #if os(iOS) if #available(iOS 9.0, *), originUrlString == nil { let temp = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("SwiftR", isDirectory: true) let jqueryTempURL = temp.appendingPathComponent("jquery-2.1.3.min.js") let signalRTempURL = temp.appendingPathComponent("jquery.signalr-\(signalRVersion).min") let jsTempURL = temp.appendingPathComponent("SwiftR.js") let fileManager = FileManager.default do { if SwiftR.connections.isEmpty { SwiftR.cleanup() try fileManager.createDirectory(at: temp, withIntermediateDirectories: false) } if !fileManager.fileExists(atPath: jqueryTempURL.path) { try fileManager.copyItem(at: jqueryURL, to: jqueryTempURL) } if !fileManager.fileExists(atPath: signalRTempURL.path) { try fileManager.copyItem(at: signalRURL, to: signalRTempURL) } if !fileManager.fileExists(atPath: jsTempURL.path) { try fileManager.copyItem(at: jsURL, to: jsTempURL) } } catch { print("Failed to copy JavaScript to temp dir: \(error)") } jqueryInclude = scriptAsSrc(jqueryTempURL) signalRInclude = scriptAsSrc(signalRTempURL) jsInclude = scriptAsSrc(jsTempURL) } #else if originUrlString == nil { // force to content regardless Origin configuration for OS X jqueryInclude = scriptAsContent(jqueryURL) signalRInclude = scriptAsContent(signalRURL) jsInclude = scriptAsContent(jsURL) } #endif let config = WKWebViewConfiguration() config.userContentController.add(self, name: "interOp") #if !os(iOS) //config.preferences.setValue(true, forKey: "developerExtrasEnabled") #endif wkWebView = WKWebView(frame: CGRect.zero, configuration: config) wkWebView.navigationDelegate = self let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude)" + "</body></html>" wkWebView.loadHTMLString(html, baseURL: baseHTMLUrl) } else { let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude)" + "</body></html>" webView = SwiftRWebView() #if os(iOS) webView.delegate = self webView.loadHTMLString(html, baseURL: baseHTMLUrl) #else webView.policyDelegate = self webView.mainFrame.loadHTMLString(html, baseURL: baseHTMLUrl) #endif } if let ua = customUserAgent { applyUserAgent(ua) } SwiftR.connections.append(self) } deinit { if let view = wkWebView { view.removeFromSuperview() } } open func createHubProxy(_ name: String) -> Hub { let hub = Hub(name: name, connection: self) hubs[name.lowercased()] = hub return hub } open func addHub(_ hub: Hub) { hub.connection = self hubs[hub.name.lowercased()] = hub } open func send(_ data: Any?) { var json = "null" if let d = data { if let val = SignalR.stringify(d) { json = val } } runJavaScript("swiftR.connection.send(\(json))") } open func start() { if ready { runJavaScript("start()") } else { connect() } } open func stop() { runJavaScript("swiftR.connection.stop()") } func shouldHandleRequest(_ request: URLRequest) -> Bool { if request.url!.absoluteString.hasPrefix("swiftr://") { let id = (request.url!.absoluteString as NSString).substring(from: 9) let msg = webView.stringByEvaluatingJavaScript(from: "readMessage('\(id)')")! let data = msg.data(using: String.Encoding.utf8, allowLossyConversion: false)! let json = try! JSONSerialization.jsonObject(with: data, options: []) if let m = json as? [String: Any] { processMessage(m) } return false } return true } func processMessage(_ json: [String: Any]) { if let message = json["message"] as? String { switch message { case "ready": let isHub = connectionType == .hub ? "true" : "false" runJavaScript("swiftR.transport = '\(transport.stringValue)'") runJavaScript("initialize('\(baseUrl)', \(isHub))") readyHandler(self) runJavaScript("start()") case "starting": state = .connecting starting?() case "connected": state = .connected connectionID = json["connectionId"] as? String connected?() case "disconnected": state = .disconnected disconnected?() case "connectionSlow": connectionSlow?() case "connectionFailed": connectionFailed?() case "reconnecting": state = .connecting reconnecting?() case "reconnected": state = .connected reconnected?() case "invokeHandler": let hubName = json["hub"] as! String if let hub = hubs[hubName] { let uuid = json["id"] as! String let result = json["result"] let error = json["error"] as AnyObject? if let callback = hub.invokeHandlers[uuid] { callback(result as AnyObject?, error) hub.invokeHandlers.removeValue(forKey: uuid) } else if let e = error { print("SwiftR invoke error: \(e)") } } case "error": if let err = json["error"] as? [String: Any] { error?(err) } else { error?(nil) } default: break } } else if let data: Any = json["data"] { received?(data) } else if let hubName = json["hub"] as? String { let callbackID = json["id"] as? String let method = json["method"] as? String let arguments = json["arguments"] as? [AnyObject] let hub = hubs[hubName] if let method = method, let callbackID = callbackID, let handlers = hub?.handlers[method], let handler = handlers[callbackID] { handler(arguments) } } } func runJavaScript(_ script: String, callback: ((Any?) -> ())? = nil) { guard wkWebView != nil || webView != nil else { jsQueue.append((script, callback)) return } if useWKWebView { wkWebView.evaluateJavaScript(script, completionHandler: { (result, _) in callback?(result) }) } else { let result = webView.stringByEvaluatingJavaScript(from: script) callback?(result as AnyObject!) } } func applyUserAgent(_ userAgent: String) { #if os(iOS) if useWKWebView { if #available(iOS 9.0, *) { wkWebView.customUserAgent = userAgent } else { print("Unable to set user agent for WKWebView on iOS <= 8. Please register defaults via NSUserDefaults instead.") } } else { print("Unable to set user agent for UIWebView. Please register defaults via NSUserDefaults instead.") } #else if useWKWebView { if #available(OSX 10.11, *) { wkWebView.customUserAgent = userAgent } else { print("Unable to set user agent for WKWebView on OS X <= 10.10.") } } else { webView.customUserAgent = userAgent } #endif } // MARK: - WKNavigationDelegate // http://stackoverflow.com/questions/26514090/wkwebview-does-not-run-javascriptxml-http-request-with-out-adding-a-parent-vie#answer-26575892 open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { #if os(iOS) UIApplication.shared.keyWindow?.addSubview(wkWebView) #endif } // MARK: - WKScriptMessageHandler open func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if let id = message.body as? String { wkWebView.evaluateJavaScript("readMessage('\(id)')", completionHandler: { [weak self] (msg, err) in if let m = msg as? [String: Any] { self?.processMessage(m) } else if let e = err { print("SwiftR unable to process message \(id): \(e)") } else { print("SwiftR unable to process message \(id)") } }) } } // MARK: - Web delegate methods #if os(iOS) open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { return shouldHandleRequest(request) } #else public func webView(_ webView: WebView!, decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) { if shouldHandleRequest(request as URLRequest) { listener.use() } } #endif class func stringify(_ obj: Any) -> String? { // Using an array to start with a valid top level type for NSJSONSerialization let arr = [obj] if let data = try? JSONSerialization.data(withJSONObject: arr, options: JSONSerialization.WritingOptions()) { if let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? { // Strip the array brackets to be left with the desired value let range = str.index(str.startIndex, offsetBy: 1) ..< str.index(str.endIndex, offsetBy: -1) return String(str[range]) } } return nil } } // MARK: - Hub open class Hub: NSObject { let name: String var handlers: [String: [String: ([Any]?) -> ()]] = [:] var invokeHandlers: [String: (_ result: Any?, _ error: AnyObject?) -> ()] = [:] var connection: SignalR! public init(_ name: String) { self.name = name self.connection = nil } init(name: String, connection: SignalR) { self.name = name self.connection = connection } open func on(_ method: String, callback: @escaping ([Any]?) -> ()) { let callbackID = UUID().uuidString if handlers[method] == nil { handlers[method] = [:] } handlers[method]?[callbackID] = callback } func initialize() { for (method, callbacks) in handlers { callbacks.forEach { connection.runJavaScript("addHandler('\($0.key)', '\(name)', '\(method)')") } } } open func invoke(_ method: String, arguments: [Any]? = nil, callback: ((_ result: Any?, _ error: Any?) -> ())? = nil) throws { guard connection != nil else { throw SwiftRError.notConnected } var jsonArguments = [String]() if let args = arguments { for arg in args { if let val = SignalR.stringify(arg) { jsonArguments.append(val) } else { jsonArguments.append("null") } } } let args = jsonArguments.joined(separator: ", ") let uuid = UUID().uuidString if let handler = callback { invokeHandlers[uuid] = handler } let doneJS = "function() { postMessage({ message: 'invokeHandler', hub: '\(name.lowercased())', id: '\(uuid)', result: arguments[0] }); }" let failJS = "function() { postMessage({ message: 'invokeHandler', hub: '\(name.lowercased())', id: '\(uuid)', error: processError(arguments[0]) }); }" let js = args.isEmpty ? "ensureHub('\(name)').invoke('\(method)').done(\(doneJS)).fail(\(failJS))" : "ensureHub('\(name)').invoke('\(method)', \(args)).done(\(doneJS)).fail(\(failJS))" connection.runJavaScript(js) } } public enum SignalRVersion : CustomStringConvertible { case v2_2_2 case v2_2_1 case v2_2_0 case v2_1_2 case v2_1_1 case v2_1_0 case v2_0_3 case v2_0_2 case v2_0_1 case v2_0_0 public var description: String { switch self { case .v2_2_2: return "2.2.2" case .v2_2_1: return "2.2.1" case .v2_2_0: return "2.2.0" case .v2_1_2: return "2.1.2" case .v2_1_1: return "2.1.1" case .v2_1_0: return "2.1.0" case .v2_0_3: return "2.0.3" case .v2_0_2: return "2.0.2" case .v2_0_1: return "2.0.1" case .v2_0_0: return "2.0.0" } } } #if os(iOS) typealias SwiftRWebView = UIWebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, UIWebViewDelegate {} #else typealias SwiftRWebView = WebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, WebPolicyDelegate {} #endif
mit
9ad5f6d959e8eaea908a5a2da032d576
34.276451
214
0.534007
4.867436
false
false
false
false
tombcz/numberthink
NumberThink/WordListView.swift
1
3255
import UIKit class WordListView: UIView, UITableViewDelegate, UITableViewDataSource, WordListCellDelegate { @IBOutlet weak var TableView: UITableView! var items: [WordListItem] = [] @IBOutlet var contentView: UIView! override init(frame:CGRect) { super.init(frame:frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) commonInit() } private func commonInit() { Bundle.main.loadNibNamed("WordListView", owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] TableView.register(WordListCell.self, forCellReuseIdentifier: "cell") let dict = Csv.readWords() for (k,v) in (Array(dict).sorted {Int($0.1)! < Int($1.1)!}) { items.append(WordListItem(text:k, number:v)) } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! WordListCell cell.listItems = items[indexPath.row] cell.selectionStyle = UITableViewCellSelectionStyle.none cell.delegate = self return cell } // MARK: - TableViewCellDelegate methods func cellDidBeginEditing(_ editingCell: WordListCell) { let editingOffset = self.TableView.contentOffset.y - editingCell.frame.origin.y as CGFloat let visibleCells = self.TableView.visibleCells as! [WordListCell] for cell in visibleCells { UIView.animate(withDuration: 0.3, animations: { () -> Void in cell.transform = CGAffineTransform(translationX: 0, y: editingOffset) if cell != editingCell { cell.alpha = 0.3 } }) } } func cellDidEndEditing(_ editingCell: WordListCell) { if editingCell.listItems?.text == "" { editingCell.listItems?.text = editingCell.origWord } if editingCell.listItems?.text != editingCell.origWord { Csv.update(word:editingCell.origWord, newWord:(editingCell.listItems?.text)!) } let visibleCells = self.TableView.visibleCells as! [WordListCell] let lastView = visibleCells[visibleCells.count - 1] as WordListCell for cell: WordListCell in visibleCells { UIView.animate(withDuration: 0.3, animations: { () -> Void in cell.transform = CGAffineTransform.identity if cell != editingCell { cell.alpha = 1.0 } }, completion: { (Finished: Bool) -> Void in if cell == lastView { self.TableView.reloadData() } }) } } }
mit
2c0edd759caaf0110ff67f7e558fbc63
33.62766
100
0.601536
5.085938
false
false
false
false
qinting513/SwiftNote
youtube/YouTube/Supporting views/CustomCollectionViewCell.swift
1
2211
// // CustomCollectionViewCell.swift // YouTube // // Created by Haik Aslanyan on 6/23/16. // Copyright © 2016 Haik Aslanyan. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { //MARK: Properties @IBOutlet weak var channelPic: UIButton! @IBOutlet weak var videoPic: UIImageView! @IBOutlet weak var videoTitle: UILabel! @IBOutlet weak var videoDescription: UILabel! @IBOutlet weak var videoDuration: UILabel! @IBOutlet weak var separatorView: UIView! //MARK: Methods func customization() { self.channelPic.layer.cornerRadius = 24 self.channelPic.clipsToBounds = true self.videoDuration.backgroundColor = UIColor.black.withAlphaComponent(0.5) self.videoDuration.layer.borderWidth = 0.5 self.videoDuration.layer.borderColor = UIColor.white.cgColor self.videoDuration.sizeToFit() } //MARK: Methods func resetCell() { self.separatorView.isHidden = false self.videoPic.image = UIImage.init(named: "emptyTumbnail") self.videoTitle.text = "" self.channelPic.setImage(UIImage(), for: []) self.videoDuration.text = "" self.videoDescription.text = "" } func setupCell(videoItem: VideoItem) { self.videoPic.image = videoItem.tumbnail self.videoTitle.text = videoItem.title self.channelPic.setImage(videoItem.channel.image, for: []) self.channelPic.imageView?.contentMode = UIViewContentMode.scaleAspectFill self.videoDuration.text = " " + secondsToHoursMinutesSeconds(seconds: videoItem.duration) + " " let viewsCount = NumberFormatter() viewsCount.numberStyle = .decimal let views = viewsCount.string(from: videoItem.views as NSNumber)! let description = videoItem.channel.name + " • " + views self.videoDescription.text = description } //MARK: Inits override func awakeFromNib() { super.awakeFromNib() customization() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
apache-2.0
69ca31fd0fd3e281970929c850b540e0
32.454545
103
0.648098
4.590437
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/UITestsFoundation/Screens/Editor/BlockEditorScreen.swift
1
9773
import ScreenObject import XCTest import XCUITestHelpers public class BlockEditorScreen: ScreenObject { let editorCloseButtonGetter: (XCUIApplication) -> XCUIElement = { $0.navigationBars["Gutenberg Editor Navigation Bar"].buttons["Close"] } var editorCloseButton: XCUIElement { editorCloseButtonGetter(app) } let addBlockButtonGetter: (XCUIApplication) -> XCUIElement = { $0.buttons["add-block-button"] // Uses a testID } var addBlockButton: XCUIElement { addBlockButtonGetter(app) } let moreButtonGetter: (XCUIApplication) -> XCUIElement = { $0.buttons["more_post_options"] } var moreButton: XCUIElement { moreButtonGetter(app) } public init(app: XCUIApplication = XCUIApplication()) throws { // The block editor has _many_ elements but most are loaded on-demand. To verify the screen // is loaded, we rely only on the button to add a new block and on the navigation bar we // expect to encase the screen. try super.init( expectedElementGetters: [ editorCloseButtonGetter, addBlockButtonGetter ], app: app, waitTimeout: 10 ) } /** Enters text into title field. - Parameter text: the test to enter into the title */ public func enterTextInTitle(text: String) -> BlockEditorScreen { let titleView = app.otherElements["Post title. Empty"].firstMatch // Uses a localized string titleView.tap() titleView.typeText(text) return self } /** Adds a paragraph block with text. - Parameter withText: the text to enter in the paragraph block */ public func addParagraphBlock(withText text: String) -> BlockEditorScreen { addBlock("Paragraph block") let paragraphView = app.otherElements["Paragraph Block. Row 1. Empty"].textViews.element(boundBy: 0) paragraphView.typeText(text) return self } /** Adds an image block with latest image from device. */ public func addImage() throws -> BlockEditorScreen { addBlock("Image block") try addImageByOrder(id: 0) return self } /** Adds a gallery block with multiple images from device. */ public func addImageGallery() throws -> BlockEditorScreen { addBlock("Gallery block") try addMultipleImages(numberOfImages: 3) return self } /** Selects a block based on part of the block label (e.g. partial text in a paragraph block) */ @discardableResult public func selectBlock(containingText text: String) -> BlockEditorScreen { let predicate = NSPredicate(format: "label CONTAINS[c] '\(text)'") XCUIApplication().buttons.containing(predicate).firstMatch.tap() return self } // returns void since return screen depends on from which screen it loaded public func closeEditor() { XCTContext.runActivity(named: "Close the block editor") { (activity) in XCTContext.runActivity(named: "Close the More menu if needed") { (activity) in let actionSheet = app.sheets.element(boundBy: 0) if actionSheet.exists { dismissBlockEditorPopovers() } } // Wait for close button to be hittable (i.e. React "Loading from pre-bundled file" message is gone) editorCloseButton.waitForIsHittable(timeout: 3) editorCloseButton.tap() XCTContext.runActivity(named: "Discard any local changes") { (activity) in guard app.staticTexts["You have unsaved changes."].waitForIsHittable(timeout: 3) else { return } Logger.log(message: "Discarding unsaved changes", event: .v) let discardButton = app.buttons["Discard"] // Uses a localized string discardButton.tap() } let editorNavBar = app.navigationBars["Gutenberg Editor Navigation Bar"] let waitForEditorToClose = editorNavBar.waitFor(predicateString: "isEnabled == false") XCTAssertEqual(waitForEditorToClose, .completed, "Block editor should be closed but is still loaded.") } } // Sometimes ScreenObject times out due to long loading time making the Editor Screen evaluate to `nil`. // This function adds the ability to still close the Editor Screen when that happens. public static func closeEditorDiscardingChanges(app: XCUIApplication = XCUIApplication()) { let closeButton = app.buttons["Close"] if closeButton.waitForIsHittable() { closeButton.tap() } let discardChangesButton = app.buttons["Discard"] if discardChangesButton.waitForIsHittable() { discardChangesButton.tap() } } public func publish() throws -> EditorNoticeComponent { let publishButton = app.buttons["Publish"] let publishNowButton = app.buttons["Publish Now"] var tries = 0 // This loop to check for Publish Now Button is an attempt to confirm that the publishButton.tap() call took effect. // The tests would fail sometimes in the pipeline with no apparent reason. repeat { publishButton.tap() tries += 1 } while !publishNowButton.waitForIsHittable(timeout: 3) && tries <= 3 try confirmPublish() return try EditorNoticeComponent(withNotice: "Post published", andAction: "View") } public func openPostSettings() throws -> EditorPostSettings { moreButton.tap() let postSettingsButton = app.buttons["Post Settings"] // Uses a localized string postSettingsButton.tap() return try EditorPostSettings() } private func getContentStructure() -> String { moreButton.tap() let contentStructure = app.staticTexts.element(matching: NSPredicate(format: "label CONTAINS 'Content Structure'")).label dismissBlockEditorPopovers() return contentStructure } private func dismissBlockEditorPopovers() { if XCUIDevice.isPad { app.otherElements["PopoverDismissRegion"].tap() dismissImageViewIfNeeded() } else { app.buttons["Keep Editing"].tap() } } private func dismissImageViewIfNeeded() { let fullScreenImage = app.images["Fullscreen view of image. Double tap to dismiss"] if fullScreenImage.exists { fullScreenImage.tap() } } @discardableResult public func verifyContentStructure(blocks: Int, words: Int, characters: Int) throws -> BlockEditorScreen { let expectedStructure = "Content Structure Blocks: \(blocks), Words: \(words), Characters: \(characters)" let actualStructure = getContentStructure() XCTAssertEqual(actualStructure, expectedStructure, "Unexpected post structure.") return try BlockEditorScreen() } private func addBlock(_ blockLabel: String) { addBlockButton.tap() let blockButton = app.buttons[blockLabel] XCTAssertTrue(blockButton.waitForIsHittable(timeout: 3)) blockButton.tap() } /// Some tests might fail during the block picking flow. In such cases, we need to dismiss the /// block picker itself before being able to interact with the rest of the app again. public func dismissBlocksPickerIfNeeded() { // Determine whether the block picker is on screen using the visibility of the add block // button as a proxy guard addBlockButton.isFullyVisibleOnScreen() == false else { return } // Dismiss the block picker by swiping down app.swipeDown() XCTAssertTrue(addBlockButton.waitForIsHittable(timeout: 3)) } /* Select Image from Camera Roll by its ID. Starts with 0 */ private func addImageByOrder(id: Int) throws { try chooseFromDevice() .selectImage(atIndex: 0) } /* Select Sequencial Images from Camera Roll by its ID. Starts with 0 */ private func addMultipleImages(numberOfImages: Int) throws { try chooseFromDevice() .selectMultipleImages(numberOfImages) } private func chooseFromDevice() throws -> MediaPickerAlbumScreen { let imageDeviceButton = app.buttons["Choose from device"] // Uses a localized string imageDeviceButton.tap() // Allow access to device media app.tap() // trigger the media permissions alert handler return try MediaPickerAlbumListScreen() .selectAlbum(atIndex: 0) } private func confirmPublish() throws { if FancyAlertComponent.isLoaded() { try FancyAlertComponent().acceptAlert() } else { let publishNowButton = app.buttons["Publish Now"] publishNowButton.tap() dismissBloggingRemindersAlertIfNeeded() } } public func dismissBloggingRemindersAlertIfNeeded() { guard app.buttons["Set reminders"].waitForExistence(timeout: 3) else { return } if XCUIDevice.isPad { app.swipeDown(velocity: .fast) } else { let dismissBloggingRemindersAlertButton = app.buttons.element(boundBy: 0) dismissBloggingRemindersAlertButton.tap() } } static func isLoaded() -> Bool { (try? BlockEditorScreen().isLoaded) ?? false } @discardableResult public func openBlockPicker() throws -> BlockEditorScreen { addBlockButton.tap() return try BlockEditorScreen() } @discardableResult public func closeBlockPicker() throws -> BlockEditorScreen { editorCloseButton.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0)).tap() return try BlockEditorScreen() } }
gpl-2.0
df87e35f921007df111a5d7bdf201cab
35.330855
129
0.656196
4.91847
false
false
false
false
chitaranjan/Album
MYAlbum/MYAlbum/ViewController.swift
1
274043
// // ViewController.swift // MYAlbum // // Created by Chitaranjan Sahu on 07/03/17. // Copyright © 2017 Ithink. All rights reserved. // import UIKit import Photos import AVKit import NYTPhotoViewer import Letters import Alamofire import SDWebImage import DKImagePickerController import NVActivityIndicatorView //import SABlurImageView let SCREENHEIGHT = UIScreen.main.bounds.height let SCREENWIDTH = UIScreen.main.bounds.width let cache = NSCache<NSString, UIImage>() let font = UIFont(name: "Raleway-Light", size: 18) let subfont = UIFont(name: "Raleway-Regular", size: 14) class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDelegateFlowLayout,NVActivityIndicatorViewable,SetPartitionAfterInsideUpload,SaveDescriptionDelegate,autoScrollDelegate,UITextFieldDelegate,SaveCoverTitleDelegate { let MAX : UInt32 = 999999999 let MIN : UInt32 = 1 let TXTMAX : UInt64 = 99999999999999 let TXTMIN : UInt64 = 1 @IBOutlet var keyboardView: UIView! lazy var collectionView :UICollectionView = { let layout = ZLBalancedFlowLayout() layout.setPartitionDelegate = self layout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width , height: UIScreen.main.bounds.height) layout.footerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2) layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) layout.minimumLineSpacing = 2 layout.minimumInteritemSpacing = 2 var collectionView = UICollectionView(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.width, height: self.view.frame.height), collectionViewLayout: layout) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor.white collectionView.alwaysBounceVertical = true collectionView.bounces = true collectionView.register(UINib(nibName: "ImageCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: self.cellIdentifier) collectionView.register(UINib(nibName: "TextCellStory", bundle: nil), forCellWithReuseIdentifier: self.cellTextIdentifier) collectionView.register(UINib(nibName: "PictureHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView") collectionView.register(UINib(nibName: "FooterReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FotterView") return collectionView }() var editTurnOn = false var upload = false lazy var singleTap: UITapGestureRecognizer = { var singleTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.uploadCoverImageBtnAction)) singleTap.numberOfTapsRequired = 1 return singleTap }() lazy var barButtonActivityIndicator : NVActivityIndicatorView = { var barButtonActivityIndicator = NVActivityIndicatorView.init(frame: CGRect(x:30, y:30, width: 30, height: 30)) barButtonActivityIndicator.type = .semiCircleSpin barButtonActivityIndicator.tintColor = UIColor.white return barButtonActivityIndicator }() var sourceCell :UICollectionViewCell? // after upload collection view scroll var scrollToPostionAfterUpload = 0 lazy var scrollViewForColors :UIScrollView = { var colors = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: SCREENWIDTH - 60, height: self.editToolBar.frame.size.height)) colors.showsVerticalScrollIndicator = false colors.showsHorizontalScrollIndicator = false colors.backgroundColor = UIColor.white // CGSize(width: width, height: self.editToolBar.frame.size.height) return colors }() typealias partitionType = Array<Array<Array<String>>> //UIView *lineView; var cellsToMove0 = NSMutableArray.init() var selectedIndexPath = 0 var colorCodeArray = ["#c6bfe5","#1f1f1f","#686869","#7a797d","#645c64","#19B5FE","#87D37C","#FDE3A7","#EB974E","#6C7A89","#1BA39C"] lazy var editToolBar: UIToolbar = { var edit = UIToolbar(frame: CGRect(x: 0, y: SCREENHEIGHT - 50, width: SCREENWIDTH, height: 50)) return edit }() lazy var autoBarButton:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "Auto", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 0 return element }() lazy var threeToTwo:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "3:2", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 1 return element }() lazy var twoToThree:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "2:3", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 2 return element }() lazy var oneToOne:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "3:1", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 3 return element }() lazy var threeToOne:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "1:1", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 4 return element }() lazy var oneToThree:UIBarButtonItem = { var element = UIBarButtonItem.init(title: "1:3", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.changeAspectRatioOfSelectedItem(_:))) element.tag = 5 return element }() lazy var editToolbarItemDoneshape:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "check"), landscapeImagePhone: UIImage(named: "check"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.turnOnEditMode)) return upload }() lazy var uploadMorePhotoButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "img-album"), landscapeImagePhone: UIImage(named: "img-album"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(morePhotoUpload)) return upload }() lazy var addTextButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "typ-cursor"), landscapeImagePhone: UIImage(named: "typ-cursor"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(addTextCell)) return upload }() lazy var leftAlign:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignL"), landscapeImagePhone: UIImage(named: "AlignL"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 0 return upload }() lazy var centered:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignM"), landscapeImagePhone: UIImage(named: "AlignM"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 1 return upload }() lazy var rightAlign:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "rightA"), landscapeImagePhone: UIImage(named: "rightA"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 2 return upload }() lazy var justify:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignF"), landscapeImagePhone: UIImage(named: "AlignF"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(alignTextInTextCell(_:))) upload.tag = 3 return upload }() lazy var backBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "ios-previous"), landscapeImagePhone: UIImage(named: "ios-previous"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.cancelClicked)) return upload }() lazy var moreButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "ios-more"), landscapeImagePhone: UIImage(named: "ios-more"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.dontDoAnything)) return upload }() lazy var shareButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "share"), landscapeImagePhone: UIImage(named: "share"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.dontDoAnything)) return upload }() lazy var editTextCellButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "edit"), landscapeImagePhone: UIImage(named: "edit"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.addTitleToTextCell)) return upload }() lazy var editToolbarItemDone:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "check"), landscapeImagePhone: UIImage(named: "check"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.editToolbarConfigurationForTextCells)) upload.tintColor = UIColor.green return upload }() lazy var coverBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "profile-1"), landscapeImagePhone: UIImage(named: "profile-1"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.setCoverPhoto(_:))) return upload }() lazy var shapeBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "shape"), landscapeImagePhone: UIImage(named: "shape"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.setToolbarConfigurationForShapeOfCells)) return upload }() // lazy var deleteBarButton1:UIBarButtonItem = { // var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.trash, target: self, action: #selector(ViewController.dontDoAnything)) // // return upload // }() lazy var alignmentButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "AlignM"), landscapeImagePhone: UIImage(named: "AlignM"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.editToolbarConfigurationForTextAlignment)) return upload }() lazy var colorButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "color"), landscapeImagePhone: UIImage(named: "color"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.editToolbarForTextCellColor)) return upload }() lazy var deleteBarButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.trash, target: self, action: #selector(ViewController.deleteSelectedItem(_:))) return upload }() lazy var fixedSpace:UIBarButtonItem = { var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: self, action: #selector(ViewController.dontDoAnything)) return upload }() lazy var flexibleSpace:UIBarButtonItem = { var upload = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) return upload }() lazy var editButton:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "edit"), landscapeImagePhone: UIImage(named: "edit"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.turnOnEditMode)) return upload }() lazy var closeEdit:UIBarButtonItem = { var upload = UIBarButtonItem.init(image: UIImage(named: "ui-cross_1"), landscapeImagePhone: UIImage(named: "ui-cross_1"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.closeEditInStory)) return upload }() var cellsToMove1 = NSMutableArray.init() var lineView : UIView = UIView(frame: CGRect.zero) var localPartition = Array<Array<Array<String>>>() let CustomEverythingPhotoIndex = 1, DefaultLoadingSpinnerPhotoIndex = 3, NoReferenceViewPhotoIndex = 4 fileprivate var imageCount : NSNumber = 0 var requestOptions = PHImageRequestOptions() var requestOptionsVideo = PHVideoRequestOptions() fileprivate var videoCount : NSNumber = 0 var mutablePhotos: [ExamplePhoto] = [] var originalIndexPath: IndexPath? var swapImageView: UIImageView? var stopped : Bool = false var storyId :String = "" var storyImageUrl :String = "" var editingTextFieldIndex = Int.init() var selectedItemIndex = Int.init() let defaults = UserDefaults.standard var swapView: UIView? var draggingIndexPath: IndexPath? var frameOfDragingIndexPath : CGPoint? var draggingView: UIView? var coverdata : UIImage? var dragOffset = CGPoint.zero var longPressGesture : UILongPressGestureRecognizer? fileprivate var images = [UIImage](), needsResetLayout = false let PrimaryImageName = "NYTimesBuilding" let PlaceholderImageName = "NYTimesBuildingPlaceholder" fileprivate let cellIdentifier = "ImageCell", headerIdentifier = "header", footerIdentifier = "footer" fileprivate let cellTextIdentifier = "TextCell" var collectionArray = [[AnyHashable:Any]]() var headerView : PictureHeaderCollectionReusableView? var originalYOffset = CGFloat() //storyDetails var creatingStory = false var viewStoryId = 0 var writen_by = "" var story_cover_photo_path = "" var story_cover_photo_code = "" var story_cover_photo_slice_code = "" var story_json = [[String:AnyObject]]() var isViewStory = false var isLoadingStory = true var isFirstTime = false var reloadHeaderView = true var storyTitle = "" var storySubtitle = "" var headerCellTextFieldEditing = false //var pickerController: GMImagePickerCon! // var assets: [DKAsset]? // MARK:- ViewLifeCycle override func viewDidLoad() { super.viewDidLoad() selectedItemIndex = -1 editingTextFieldIndex = -1 defaults.set(false, forKey: "isViewStory") if creatingStory{ defaults.set(true, forKey: "FirstTimeUpload") self.IbaOpenGallery() } defaults.removeObject(forKey: "partition") defaults.removeObject(forKey: "addedMorePhotos") defaults.set(false, forKey: "insideUploads") defaults.synchronize() self.registerForKeyboardNotifications() //flag for story View or not if !isViewStory{ if storyId == ""{ storyId = String(randomNumber()) }else{ isViewStory = true editTurnOn = false self.loadCoverImage(imageUrl: story_cover_photo_path, completion: { (image) in guard let image = image else { self.navigationController?.popViewController(animated: true) return } DispatchQueue.main.async { self.coverdata = image self.isLoadingStory = true var coverImg = [AnyHashable:Any]() coverImg.updateValue(self.story_cover_photo_path, forKey: "cloudFilePath") coverImg.updateValue(0, forKey: "cover") coverImg.updateValue(self.story_cover_photo_path, forKey: "filePath") //coverImg.updateValue( (dataArray.first?["color_codes"]!)! , forKey: "hexCode") // uploadData[0].updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176" as AnyObject, forKey: "hexCode") let height = self.coverdata?.size.height let width = self.coverdata?.size.width let sizeImage = CGSize(width: width!, height: height!) coverImg.updateValue(sizeImage, forKey: "item_size") coverImg.updateValue(self.story_cover_photo_path, forKey: "item_url") coverImg.updateValue("img", forKey: "type") self.collectionArray.append(coverImg) self.view.addSubview(self.collectionView) self.collectionView.reloadData() self.setUI() } self.getDetailStoryWithId(storyId: self.storyId) { runOnMainThread { self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.isViewStory = true self.isLoadingStory = false self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() } } }) } }else{ //not view } } override func viewWillAppear(_ animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { self.creatingStory = false self.editTurnOn = false self.upload = false NotificationCenter.default.removeObserver(self) self.deRegisterForKeyboardNotifications() } func loadCoverImage(imageUrl:String,completion: @escaping ((_ data: UIImage?) -> Void)) { if let cachedVersion = cache.object(forKey: "\(imageUrl)" as NSString) { completion(cachedVersion) }else{ let manager: SDWebImageManager = SDWebImageManager.shared() manager.imageDownloader?.downloadImage(with: URL(string: imageUrl), options: [], progress: { (receivedSize, expectedSize, url) in }, completed: { (image, data, error, finished) in if error != nil{ completion(nil) } guard let data = data, error == nil else { return } guard let image = image, error == nil else { return } cache.setObject(image, forKey: "\(imageUrl)" as NSString) completion(image) }) } } func setCoverPhoto(_ sender: UIBarButtonItem) { let alertView = UIAlertController(title: "Cover photo", message: "Do you want to use this photo as the cover photo of your album.", preferredStyle: .alert) let action = UIAlertAction(title: "Yes", style: .default, handler: { (alert) in if let headerAttributes = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)){ let data = self.collectionArray[self.selectedItemIndex] if let story_cover_photo_path = data["item_url"] as? String { var url = story_cover_photo_path var urlImage = url.components(separatedBy: "album") let totalPath = URLConstants.imgDomain if urlImage.count == 2 { let second = urlImage[1] url = totalPath + second }else{ if let first = urlImage.first{ url = totalPath + first } } self.story_cover_photo_path = url //url = totalPath + (urlImage?[1])! var version = url.components(separatedBy: "compressed") var afterAppending = url.components(separatedBy: "compressed") var widthImage = (version.first)! + "1080" + (afterAppending[1]) DispatchQueue.global(qos: .background).async { self.headerView?.iboHeaderImage.sd_setImage(with: URL(string: widthImage), placeholderImage: UIImage(named: ""), options: SDWebImageOptions.progressiveDownload, completed: { (image, data, error, finished) in guard let image = image else { return } print("Image loaded!") self.headerView?.iboHeaderImage.contentMode = UIViewContentMode.scaleAspectFill self.headerView?.iboHeaderImage.image = image self.coverdata = image DispatchQueue.main.async { self.collectionView.reloadData() self.collectionView.setContentOffset(CGPoint(x: 0, y: (headerAttributes.frame.origin.x)), animated: true) } }) } } self.collectionView.setContentOffset(CGPoint(x: 0, y: (headerAttributes.frame.origin.x)), animated: true) } }) let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { (alert) in }) alertView.addAction(action) alertView.addAction(cancel) self.present(alertView, animated: true, completion: nil) } // MARK:-shape images func setToolbarConfigurationForShapeOfCells() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [autoBarButton,fixedSpace,threeToTwo,fixedSpace,twoToThree,fixedSpace,oneToOne,flexibleSpace,threeToOne,flexibleSpace,oneToThree,flexibleSpace,editToolbarItemDoneshape] } func setBackgroundColorForTextCell(_ sender:UIButton) { let hexCodeBg = self.colorCodeArray[sender.tag] self.collectionArray[self.selectedItemIndex]["backgroundColor"] = hexCodeBg guard let cell = self.collectionView.cellForItem(at: IndexPath(item: selectedItemIndex, section: 0)) as? TextCellStoryCollectionViewCell else{return} let screenshotOfTextCell = screenShotOfView(of: cell) if let TextCell = screenshotOfTextCell{ self.collectionArray[selectedIndexPath].updateValue(TextCell, forKey: "text_image") } DispatchQueue.main.async { self.collectionView.reloadItems(at: [IndexPath(item: self.selectedItemIndex, section: 0)]) } } func alignTextInTextCell(_ sender: UIBarButtonItem) { switch sender.tag { case 0: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 0 case 1: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 1 case 2: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 2 case 3: self.collectionArray[self.selectedItemIndex]["textAlignment"] = 3 default: break } guard let cell = self.collectionView.cellForItem(at: IndexPath(item: selectedItemIndex, section: 0)) as? TextCellStoryCollectionViewCell else{return} let screenshotOfTextCell = screenShotOfView(of: cell) if let TextCell = screenshotOfTextCell{ self.collectionArray[selectedIndexPath].updateValue(TextCell, forKey: "text_image") } DispatchQueue.main.async { self.collectionView.reloadItems(at: [IndexPath(item: self.selectedItemIndex, section: 0)]) } } func changeAspectRatioOfSelectedItem(_ sender: UIBarButtonItem) { let item = self.collectionArray[self.selectedItemIndex] let oldSizeString = item["original_size"] as! CGSize // let oldSize = CGSizeFromString(oldSizeString) let newWidth = oldSizeString.width let newHeight = oldSizeString.height let squaredVal = newWidth * newHeight var newlySize = CGSize.init() if sender.tag == 0 { newlySize = oldSizeString }else if sender.tag == 1{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/6), widthConstant: 3, heightConstant: 2) as! CGSize }else if sender.tag == 2{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/6), widthConstant: 2, heightConstant: 3) as! CGSize }else if sender.tag == 3{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal), widthConstant: 1, heightConstant: 1) as! CGSize }else if sender.tag == 4{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/3), widthConstant: 3, heightConstant: 1) as! CGSize }else if sender.tag == 5{ newlySize = CalculationsShape.getSizeWithFloatValue(number: Float(squaredVal/3), widthConstant: 1, heightConstant: 3) as! CGSize } self.collectionArray[self.selectedItemIndex]["item_size"] = newlySize // self.collectionArray[self.selectedItemIndex] = newObj DispatchQueue.main.async { UIView.animate(withDuration: 2.0) { // self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() } } } func deleteSelectedItem(_ sender: UIBarButtonItem) { let alertView = UIAlertController(title: "Delete item", message: "Are you sure you wish to delete this item?", preferredStyle: .alert) let action = UIAlertAction(title: "Delete", style: .default, handler: { (alert) in DispatchQueue.main.async { self.title = "" self.collectionArray.remove(at: self.selectedItemIndex) let singletonArray = self.getSingletonArray() let obj = singletonArray[self.selectedItemIndex] let keys = obj.components(separatedBy: "-") var rowArray = self.localPartition[Int(keys.first!)!] var colArray = rowArray[Int(keys[1])!] colArray.remove(at: colArray.count - 1) if colArray.count > 0{ rowArray[Int(keys[1])!] = colArray self.localPartition[Int(keys.first!)!] = rowArray }else{ rowArray.remove(at: Int(keys[1])!) if rowArray.count > 0 { self.localPartition[Int(keys.first!)!] = rowArray }else{ self.localPartition.remove(at: Int(keys.first!)!) if let first = Int(keys.first!){ for i in first ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } self.localPartition[i] = rowArray } } } } self.defaults.set(self.localPartition, forKey: "partition") self.collectionView.performBatchUpdates({ let selectedIndex = IndexPath(item: self.selectedItemIndex, section: 0) self.collectionView.deleteItems(at: [selectedIndex]) }, completion: { (flag) in self.selectedItemIndex = -1 let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() self.setInitialToolbarConfiguration() }) } }) let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { (alert) in }) alertView.addAction(action) alertView.addAction(cancel) self.present(alertView, animated: true, completion: nil) } func textFieldDidBeginEditing(_ textField: UITextField) { if textField.tag == 98 || textField.tag == 99{ headerCellTextFieldEditing = true } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.tag == 99{ self.headerView?.iboSubTitle.becomeFirstResponder() //textField.becomeFirstResponder() } if textField.tag == 98{ textField.resignFirstResponder() } return true } func textFieldDidEndEditing(_ textField: UITextField) { if textField.tag == 98{ if textField.hasText{ storySubtitle = textField.text! } headerCellTextFieldEditing = false } else if textField.tag == 99{ if textField.hasText { storyTitle = textField.text! } headerCellTextFieldEditing = false } } func randomNumber() -> Int { var random_number = Int(arc4random_uniform(MAX) + MIN) print ("random = ", random_number); return random_number } func generateTextId() -> String{ var rnd : UInt64 = TXTMIN arc4random_buf(&rnd, MemoryLayout.size(ofValue: rnd)) return String(rnd % TXTMAX) } func addTitleToTextCell() { let textViewController = storyboard?.instantiateViewController(withIdentifier: "TextViewController") as! TextViewController textViewController.delegate = self textViewController.titleText = self.collectionArray[self.selectedItemIndex]["title"] as! String textViewController.subTitleText = self.collectionArray[self.selectedItemIndex]["description"] as! String //self.collectionArray[selectedIndex]["title"] = title // self.collectionArray[selectedIndex]["description"] = subtitle textViewController.selectedIndex = self.selectedItemIndex self.present(textViewController, animated: true, completion: nil) } func saveDescriptionDidFinish(_ controller:TextViewController,title:String,subtitle:String,indexToUpdate selectedIndex:Int) { self.collectionArray[selectedIndex]["title"] = title self.collectionArray[selectedIndex]["description"] = subtitle let titleHeight = title.height(withConstrainedWidth: SCREENWIDTH - 20, font: font!) let subtitle = subtitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: subfont!) let total = CGFloat(80) + titleHeight + subtitle var size = self.collectionArray[selectedIndex]["item_size"] as! CGSize size.height = total self.collectionArray[selectedIndex]["item_size"] = size selectedItemIndex = -1 if(selectedItemIndex != selectedIndex){ var previousSelected = selectedItemIndex selectedItemIndex = selectedIndex if previousSelected != -1{ } } DispatchQueue.main.async { self.collectionView.performBatchUpdates({ self.collectionView.reloadItems(at: [IndexPath(item: selectedIndex, section: 0)]) }) { (test) in } } } func setUI() { self.fixedSpace.width = 20 DispatchQueue.main.async { self.navigationController?.navigationBar.isHidden = false self.navigationController?.isNavigationBarHidden = false self.navigationController?.navigationBar.setBackgroundImage(UIImage.init(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage.init() self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.navigationBar.backgroundColor = UIColor.clear self.navigationController?.navigationBar.alpha = 1 self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationItem.setLeftBarButton(self.backBarButton, animated: true) self.navigationItem.leftBarButtonItem?.isEnabled = true self.navigationItem.setHidesBackButton(false, animated: true) self.navigationItem.setRightBarButtonItems([self.moreButton,self.shareButton,self.editButton], animated: true) self.navigationController?.navigationBar.tintColor = UIColor.white self.setNeedsStatusBarAppearanceUpdate() self.navigationController?.navigationBar.barTintColor = UIColor.white } } func morePhotoUpload() { if self.localPartition.count > 0{ defaults.set(true, forKey: "insideUploads") }else{ defaults.set(false, forKey: "insideUploads") } self.showImagePicker() } func setPartitionAfterInsideUpload() { if let local = defaults.object(forKey: "partition") as? partitionType{ self.localPartition = local } } func setNavigationBarForViewMode() { self.editToolBar.alpha = 0 let tranction = CATransition() tranction.duration = 0.5 tranction.type = kCATransitionReveal tranction.subtype = kCATransitionFromBottom tranction.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) self.editToolBar.layer.add(tranction, forKey: "slideInFromBottomTransition") CATransaction.setCompletionBlock({ self.editToolBar.removeFromSuperview() }) // self.title = "" self.navigationController?.setNavigationBarHidden(false, animated: true) //[self.navigationController setNavigationBarHidden:NO]; self.navigationItem.setLeftBarButton(backBarButton, animated: true) self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationItem.setRightBarButtonItems([moreButton,shareButton,editButton], animated: false) self.navigationController?.navigationBar.tintColor = UIColor.white } func giveGridFrame(index: Int,frame: [String]) -> CGRect{ var rectArray = frame.map { CGRectFromString($0) } return rectArray[index] } func giveFramesFrame(index: Int,framesFrame: [String]) -> CGRect { var rectArray = framesFrame.map { CGRectFromString($0) } return rectArray[index] } func giveKeyForValue(key:String,index:Int) -> Any { var temp = self.collectionArray[index] return temp[key] } enum ImagePosition { case LEFT case BOTTOM(Int) case NOTDEFIND } func compareReturnLeftOrBottom(parant:String,child:String) -> ImagePosition { var parantKeys = parant.components(separatedBy: "-") var childKeys = child.components(separatedBy: "-") if parantKeys[0] == childKeys[0]{ if parantKeys[1] < childKeys[1]{ return .LEFT }else{ if parantKeys[2] < childKeys[2]{ return .BOTTOM(Int(childKeys[1])!) }else{ return .NOTDEFIND } } }else{ return .NOTDEFIND } } func postDataForStoryMaking() { var id = [String]() var frmaes = defaults.object(forKey: "Frames") as! [String] print("frmaes\(frmaes)") var FramesForEachRow = defaults.object(forKey: "FramesForEachRow") as! [String] print("FramesForEachRow\(FramesForEachRow)") //self.localPartition for (index,element) in self.collectionArray.enumerated(){ var element_id = element["photo_id"] as! String id.append(element_id) } let singleArray = self.getSingletonArray() var storyJsonDictonary = [[AnyHashable:Any]]() var gridHeight = 0 var gridTop = CGFloat(0) var countNoOfElement = 0 for (index,element) in self.localPartition.enumerated(){ var gridHeightDict = [AnyHashable:Any]() gridHeightDict.updateValue(gridTop, forKey: "top") gridHeightDict.updateValue(0, forKey: "left") var giveGridFrame = self.giveGridFrame(index: index, frame: FramesForEachRow) gridHeightDict.updateValue(giveGridFrame.size.height, forKey: "height") var itemsDict = [[AnyHashable:Any]]() var parant = element[0].first for(index1,element1) in element.enumerated(){ var heightForTop = CGFloat(0) var widthForLeft = CGFloat(0) for(index2,element2) in element1.enumerated(){ if element1.count > 1 && index2 > 0{ parant = element1.first } var items = [AnyHashable:Any]() let frame = self.giveFramesFrame(index: countNoOfElement, framesFrame: frmaes) let type = self.giveKeyForValue(key: "type", index: countNoOfElement) let original_size = self.giveKeyForValue(key: "original_size", index: countNoOfElement) let url = self.giveKeyForValue(key: "item_url", index: countNoOfElement) as? String ?? "" var image_Path = "" if url.contains("http"){ image_Path = url }else{ image_Path = URLConstants.imgDomain + url } // let original_height = self.giveKeyForValue(key: "dh", index: countNoOfElement) guard let typeElement = type as? String else { return } var width_CGFloat = CGFloat.init() var height_CGFloat = CGFloat.init() var factor = CGFloat.init() if typeElement == "Text"{ width_CGFloat = SCREENWIDTH height_CGFloat = (CGSizeFromString(original_size as! String).height) }else if typeElement == "video"{ let item_size = self.giveKeyForValue(key: "item_size", index: countNoOfElement) let cgsize = item_size as! CGSize width_CGFloat = cgsize.width height_CGFloat = cgsize.height factor = width_CGFloat / height_CGFloat }else{ width_CGFloat = CGFloat((original_size as! CGSize).width) height_CGFloat = CGFloat((original_size as! CGSize).height) factor = width_CGFloat / height_CGFloat } if index1 == 0 && index2 == 0 { if typeElement == "Text"{ items.updateValue(0, forKey: "left") items.updateValue(0, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(id[countNoOfElement], forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue("txt", forKey: "type") let title = self.giveKeyForValue(key: "title", index: countNoOfElement) as? String ?? "" let sub = self.giveKeyForValue(key: "description", index: countNoOfElement) as? String ?? "" let textAlignment = self.giveKeyForValue(key: "textAlignment", index: countNoOfElement) as? Int ?? 1 let backgroundColor = self.giveKeyForValue(key: "backgroundColor", index: countNoOfElement) as? String ?? "#ffffff" items.updateValue(title, forKey: "title") items.updateValue(sub, forKey: "description") items.updateValue(textAlignment, forKey: "textAlignment") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue(backgroundColor, forKey: "backgroundColor") items.updateValue("\(height_CGFloat)", forKey: "dh") // items.updateValue("\(factor)", forKey: "factor") // items.updateValue(color, forKey: "color") items.updateValue("", forKey: "below") }else{ items.updateValue(0, forKey: "left") items.updateValue(0, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(image_Path, forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue(type, forKey: "type") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue("\(height_CGFloat)", forKey: "dh") items.updateValue("\(factor)", forKey: "factor") if typeElement != "video"{ let color = self.giveKeyForValue(key: "hexCode", index: countNoOfElement) items.updateValue(color, forKey: "color") } items.updateValue("", forKey: "below") } }else{ // var sourseKeys = element2.components(separatedBy: "-") var leftOrBottom = self.compareReturnLeftOrBottom(parant: parant!, child: element2) switch leftOrBottom { case .LEFT: let leftFrame = self.giveFramesFrame(index: countNoOfElement - 1, framesFrame: frmaes) widthForLeft += leftFrame.size.width items.updateValue(widthForLeft, forKey: "left") items.updateValue(0, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(image_Path, forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue(type as! String, forKey: "type") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue("\(height_CGFloat)", forKey: "dh") items.updateValue(factor, forKey: "factor") if typeElement != "video"{ let color = self.giveKeyForValue(key: "hexCode", index: countNoOfElement) items.updateValue(color, forKey: "color") } items.updateValue("", forKey: "below") break case .BOTTOM(let postion): let index = singleArray.index(of: parant!) print(index) //let ph = self.giveKeyForValue(key: "photo_id", index: index) let photo_id = self.giveKeyForValue(key: "photo_id", index: index!) heightForTop += frame.size.height items.updateValue(widthForLeft, forKey: "left") items.updateValue(heightForTop, forKey: "top") items.updateValue(id[countNoOfElement], forKey: "id") items.updateValue(image_Path, forKey: "imagePath") items.updateValue(frame.size.width, forKey: "width") items.updateValue(frame.size.height, forKey: "height") items.updateValue(type as! String, forKey: "type") items.updateValue("\(width_CGFloat)", forKey: "dw") items.updateValue("\(height_CGFloat)", forKey: "dh") items.updateValue(factor, forKey: "factor") if typeElement != "video"{ let color = self.giveKeyForValue(key: "hexCode", index: countNoOfElement) items.updateValue(color, forKey: "color") } items.updateValue(photo_id as! String, forKey: "below") print(postion) break case .NOTDEFIND: break } } countNoOfElement += 1 print("singke element\(gridHeightDict)") print(element2) itemsDict.append(items) } } gridHeightDict.updateValue(itemsDict, forKey: "items") gridTop += giveGridFrame.size.height print("grid element\(gridHeightDict)") storyJsonDictonary.append(gridHeightDict) } print("grid element\(storyJsonDictonary)") do { let jsonData = try JSONSerialization.data(withJSONObject: storyJsonDictonary, options: .prettyPrinted) // here "jsonData" is the dictionary encoded in JSON data let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) var storyJSON = String.init(data: jsonData, encoding: String.Encoding.utf8) self.postStoryData(storyDataTosend: storyJSON!) } catch { print(error.localizedDescription) } } func dontDoAnything() { } func saveCoverTitleDidFinish(_ controller:CoverTitleViewEditViewController,title:String,subtitle:String) { if let header = self.headerView{ storyTitle = title storySubtitle = subtitle header.iboTitle.text = title header.iboSubTitle.text = subtitle } } func uploadCoverImageBtnAction() { var coverViewController = self.storyboard?.instantiateViewController(withIdentifier: "CoverTitleViewEditViewController") as! CoverTitleViewEditViewController coverViewController.delegate = self if let header = self.headerView{ coverViewController.coverImageView = self.coverdata if header.iboTitle.hasText{ coverViewController.titleText = header.iboTitle.text! } if header.iboSubTitle.hasText{ coverViewController.subTitleText = header.iboSubTitle.text! } } self.present(coverViewController, animated: true, completion: nil) } func appendStroyIdAnddetails(Params: inout [String:String]) { for (index,element) in self.collectionArray.enumerated(){ if (element["type"] as! String) != "Text"{ Params.updateValue(element["photo_id"] as! String, forKey: "story_photo[\(index)][photo_id]") let imgurl = element["item_url"] as! String let totalPath = URLConstants.imgDomain var url = "" var urlImage = imgurl.components(separatedBy: "album") if urlImage.count == 2 { var second = urlImage[1] second.remove(at: second.startIndex) url = totalPath + second }else{ let first = urlImage[0] url = totalPath + first } Params.updateValue(url , forKey: "story_photo[\(index)][photo_path]") if (element["type"] as! String) != "video"{ Params.updateValue(element["hexCode"] as! String, forKey: "story_photo[\(index)][color_codes]") } } // print(Params) } // return Params } func turnOnEditMode() { self.navigationItem.leftBarButtonItem = nil self.navigationItem.setHidesBackButton(true, animated: true) self.navigationItem.rightBarButtonItems = nil self.title = "Edit and enrich" self.navigationItem.setRightBarButton(closeEdit, animated: true) self.setInitialToolbarConfiguration() self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) editTurnOn = true isViewStory = false if self.isFirstTime{ }else{ if self.collectionView.visibleCells.count == 0 { self.collectionView.scrollToItem(at: IndexPath(item: scrollToPostionAfterUpload, section: 0), at: .centeredVertically, animated: true) } } headerView?.iboHeaderImage.addGestureRecognizer(singleTap) } func closeEditInStory() { self.postDataForStoryMaking() //self.navigationController?.navigationBar.tintColor = UIColor.black self.setNavigationBarForViewMode() self.collectionView.removeGestureRecognizer(self.longPressGesture!) headerView?.iboHeaderImage.removeGestureRecognizer(singleTap) //selectedItemIndex = -1 } @IBAction func doneClicked(_ sender: UIButton) { if headerCellTextFieldEditing{ if let headerView = self.headerView{ UIView.animate(withDuration: 0.2, animations: { headerView.titleView.frame = CGRect(x: headerView.titleView.frame.origin.x, y: self.originalYOffset, width: headerView.titleView.frame.size.width, height: headerView.titleView.frame.size.height) }) } } sender.resignFirstResponder() self.view.endEditing(true) } @IBAction func dismissViewClicked(_ sender: UIBarButtonItem) { self.navigationController?.dismiss(animated: true, completion: nil) } func startAnimation(){ let size = CGSize(width: 30, height:30) startAnimating(size, message: "Loading...", type: NVActivityIndicatorType.ballScaleRipple) } func stopAnimationLoader() { stopAnimating() } func addTextCell() { editToolBar.isUserInteractionEnabled = true var visibleIndexPath = self.collectionView.indexPathsForVisibleItems print("addtextCell\(visibleIndexPath.count)") var previousIndexPath = IndexPath.init() if visibleIndexPath.count != 0{ previousIndexPath = (visibleIndexPath[0]) }else{ previousIndexPath = IndexPath(item: 0, section: 0) } print("previu\(previousIndexPath.item)") var singletonArray = self.getSingletonArray() print("si\(singletonArray)") var originalPaths = singletonArray[previousIndexPath.item] var keys = originalPaths.components(separatedBy: "-") var destRow = Int(keys.first!) var text = "\(destRow!)-0-0" var txtCellObj = [String]() txtCellObj.append(text) var objArray = [txtCellObj] var checkObj = "\(destRow!)-0-0" var indexOfNewItem = singletonArray.index(of: checkObj) print("text path\(objArray)") self.localPartition.insert(objArray, at: destRow!) for i in (destRow! + 1) ..< self.localPartition.count{ var destPartArray = self.localPartition[i] for j in 0 ..< destPartArray.count { var colArray = destPartArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } destPartArray[j] = colArray } self.localPartition[i] = destPartArray } defaults.set(localPartition, forKey: "partition") let txtSize = CGSize(width: SCREENWIDTH, height: 200) var textDict = [AnyHashable:Any]() textDict.updateValue("Text", forKey: "type") textDict.updateValue(txtSize, forKey: "item_size") textDict.updateValue(NSStringFromCGSize(txtSize), forKey: "original_size") let generatedId = generateTextId() textDict.updateValue(generatedId, forKey: "id") textDict.updateValue(generatedId, forKey: "photo_id") textDict.updateValue(generatedId, forKey: "imagePath") textDict.updateValue("#FFFFFF", forKey: "backgroundColor") textDict.updateValue("#000000", forKey: "textColor") textDict.updateValue(1, forKey: "textAlignment") textDict.updateValue(false, forKey: "cover") textDict.updateValue("", forKey: "title") textDict.updateValue("", forKey: "description") self.collectionArray.insert(textDict, at: indexOfNewItem!) //self.collectionArray[indexOfNewItem!] = textDict editingTextFieldIndex = indexOfNewItem! selectedItemIndex = indexOfNewItem! self.collectionView.performBatchUpdates({ self.collectionView.insertItems(at: [IndexPath(item: indexOfNewItem!, section: 0)]) }, completion: { (flag) in self.collectionView.scrollToItem(at: IndexPath(item: indexOfNewItem!, section: 0), at: UICollectionViewScrollPosition.top, animated: true) self.editToolbarConfigurationForTextCells() //self.initialiseColorCodeArray guard let TextCell = self.collectionView.cellForItem(at: IndexPath(item: indexOfNewItem!, section: 0)) as? TextCellStoryCollectionViewCell else{ return } TextCell.titleLabel.placeholder = "Title" TextCell.subTitleLabel.placeholder = "Enter your story here" // TextCell.titleLabel.inputAccessoryView = self.keyboardView //TextCell.subTitleLabel.inputAccessoryView = self.keyboardView //TextCell.titleLabel.becomeFirstResponder() self.editToolBar.isUserInteractionEnabled = true }) } func setInitialToolbarConfiguration() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [uploadMorePhotoButton,addTextButton] self.editToolBar.tintColor = UIColor(hexString:"#15181B") if !editToolBar.isDescendant(of: self.view){ // self.view.addSubview(self.editToolBar) // CATransition *transition = [CATransition animation]; // transition.duration = 0.5; // transition.type = kCATransitionPush; // transition.subtype = kCATransitionFromLeft; // [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; // [parentView.layer addAnimation:transition forKey:nil]; // // [parentView addSubview:myVC.view]; self.editToolBar.alpha = 1 let tranction = CATransition() tranction.duration = 0.5 tranction.type = kCATransitionMoveIn tranction.subtype = kCATransitionFromTop tranction.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) tranction.fillMode = kCAFillModeRemoved self.editToolBar.layer.add(tranction, forKey: "slideInFromTopTransition") self.view.addSubview(self.editToolBar) CATransaction.setCompletionBlock({ }) } } func editToolbarConfigurationForTextAlignment() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [leftAlign,fixedSpace,centered,fixedSpace,rightAlign,fixedSpace,justify,flexibleSpace,editToolbarItemDone] self.editToolBar.tintColor = UIColor(red: 21/255, green: 24/255, blue: 27/255, alpha: 1) } func editToolbarForTextCellColor() { self.editToolBar.items = nil self.editToolBar.items = [flexibleSpace,editToolbarItemDone] self.addScrollViewToToolbarWithItemsArray() self.editToolBar.tintColor = UIColor(red: 21/255, green: 24/255, blue: 27/255, alpha: 1) } func addScrollViewToToolbarWithItemsArray() { var width = CGFloat(40 * self.colorCodeArray.count) scrollViewForColors.contentSize = CGSize(width: width, height: self.editToolBar.frame.size.height) var xCoordinate = 10 for i in 0 ..< self.colorCodeArray.count{ let hexCode = self.colorCodeArray[i] let colorButtonText = UIButton.init(frame: CGRect(x: xCoordinate, y: 15, width: 30, height: 30)) colorButtonText.layer.cornerRadius = 15 colorButtonText.tag = i colorButtonText.backgroundColor = UIColor(hexString: hexCode) colorButtonText.addTarget(self, action: #selector(setBackgroundColorForTextCell(_:)), for: UIControlEvents.touchUpInside) xCoordinate += 40 self.scrollViewForColors.addSubview(colorButtonText) } self.editToolBar.addSubview(scrollViewForColors) } func screenShotOfView(of inputView:UIView) -> UIImage? { UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0) inputView.layer.render(in: UIGraphicsGetCurrentContext()!) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func changeToEnrichMode() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } let dict = self.collectionArray[selectedItemIndex] if let type = dict["type"] as? String{ if type == "video"{ self.editToolBar.items = [flexibleSpace,deleteBarButton] self.title = "Video" }else{ self.editToolBar.items = [coverBarButton,flexibleSpace,shapeBarButton,deleteBarButton] self.title = "Image" } } self.editToolBar.tintColor = UIColor(red: 21/255, green: 24/255, blue: 25/255, alpha: 1) } func editToolbarConfigurationForTextCells() { self.editToolBar.items = nil if (scrollViewForColors.isDescendant(of: self.editToolBar)){ self.scrollViewForColors.removeFromSuperview() } self.editToolBar.items = [editTextCellButton,fixedSpace,alignmentButton,fixedSpace,colorButton,fixedSpace,deleteBarButton] self.editToolBar.tintColor = UIColor(hexString:"#15181B") if let cell = self.collectionView.cellForItem(at: IndexPath(item: selectedItemIndex, section: 0)) as? TextCellStoryCollectionViewCell{ let screenshotOfTextCell = screenShotOfView(of: cell) if let TextCell = screenshotOfTextCell{ var temp = self.collectionArray[selectedIndexPath] temp.updateValue(screenshotOfTextCell, forKey: "text_image") } } } //MARK :- ScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.collectionView{ self.headerView?.layoutHeaderViewForScrollViewOffset(offset: scrollView.contentOffset) } } @IBAction func displayStory(_ sender: UIButton) { defaults.set(true, forKey: "viewStory") storyId = "44" getDetailStoryWithId(storyId: storyId) { runOnMainThread { self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.view.addSubview(self.collectionView) self.isViewStory = true self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() // let set :IndexSet = [0] // self.collectionView?.reloadSections(set) //self.collectionView?.reloadSections(IndexSet(set)) } } } // MARK:- StoryCalls func getDetailStoryWithId(storyId:String,handler: ((Void) -> Void)?) { let postUrl = URLConstants.BaseURL + "storyDetails/" + storyId Alamofire.request(postUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in switch response.result { case .success(let JSON): print("Success with JSON: \(JSON)") let response = JSON as! NSDictionary let errorCode: AnyObject = response.value(forKeyPath: "error.errorCode") as! NSNumber let errorMSG = response.value(forKeyPath: "error.errorMsg") print("postURL is :", (postUrl), "response is: \(response)", "error code is \(errorCode)") let compareCode: NSNumber = 0 if errorCode as! NSNumber == compareCode{ // if(self.allHomesArray.count == 0){ //print(self.allHomesArray.count) let dataArray = response.value(forKey: "results") as! [String: AnyObject] if let Id = dataArray["story_id"] as! Int?{ self.viewStoryId = Id } if let writen = dataArray["writen_by"] as! String?{ self.writen_by = writen } if let story_cover = dataArray["story_cover_photo_path"] as! String?{ self.story_cover_photo_path = story_cover } if let photo_code = dataArray["story_cover_photo_code"] as! String?{ self.story_cover_photo_code = photo_code } if let photo_code = dataArray["story_cover_photo_slice_code"] as! String?{ self.story_cover_photo_slice_code = photo_code } if let story_heading = dataArray["story_heading"] as! String?{ self.storyTitle = story_heading } if let story_heading_description = dataArray["story_heading_description"] as! String?{ self.storySubtitle = story_heading_description } if let story_json = dataArray["story_json"] as! String?{ let json: AnyObject? = story_json.parseJSONString print("Parsed JSON: \(json!)") self.story_json = json as! [[String:AnyObject]] //story_json.parseJSONString self.populateImage(objects: self.story_json) // story_json // self.story_json = } print(self.story_json) self.getPhoto() handler?() }else { // self.activityLoaderForFirstTime.stopAnimating() // AlertView.showAlert(self, title: "OOPS!", message: errorMSG! as AnyObject) } case .failure(let error): // self.activityLoaderForFirstTime.stopAnimating() print("Request failed with error: \(error)") // Toast.show(error.localizedDescription) // AlertView.showAlert(self, title: "", message: error) } } } //MARK:- KEYBOARD NOTIFICATION func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func deRegisterForKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardNotification(notification: NSNotification) { if let userInfo = notification.userInfo { let endFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw) if let longPressGesture = self.longPressGesture{ self.collectionView.removeGestureRecognizer(longPressGesture) } let offset = SCREENHEIGHT - (endFrame?.height)! + 40 if let hederView = self.headerView{ if (hederView.iboTitle.isFirstResponder) || (hederView.iboSubTitle.isFirstResponder){ originalYOffset = (hederView.titleView.frame.origin.y) let yOffsetHeader = offset - (hederView.titleView.frame.size.height) //let movementDuration:TimeInterval = 0.3 //UIView.beginAnimations( "animateView", context: nil) //UIView.setAnimationBeginsFromCurrentState(true) //UIView.setAnimationDuration(movementDuration ) // UIView.commitAnimations() UIView.animate(withDuration: 0.4, delay: TimeInterval(0), options: animationCurve, animations: { hederView.titleView.frame = CGRect(x: hederView.titleView.frame.origin.x, y: yOffsetHeader, width: hederView.titleView.frame.size.width, height: hederView.titleView.frame.size.height) }, completion: nil) } } } } func keyboardWillHide(notification: NSNotification) { if let longPressGesture = self.longPressGesture{ self.collectionView.addGestureRecognizer(longPressGesture) } } //MARK :- Populate Story func populateImage(objects:[[String:AnyObject]]) { var localpartitionGrid = [[[String]]]() var grid = [[[String]]]() var id = [String]() for (index, element) in objects.enumerated() { let items = element["items"] as! [[String:AnyObject]] var count = 0 for (index, element) in items.enumerated() { id.append(element["id"] as! String) //count += 1 } } var i = 0 self.collectionArray.remove(at: 0) self.localPartition.removeAll(keepingCapacity: true) var partitionGrid = [[String]]() for (indexOut, element) in objects.enumerated() { var partition = [[String]]() if indexOut == 0{} let item = element["items"] as! [[String:AnyObject]] var belowCount = 0 var leftCount = 0 var belowObject = [String]() var search = [String: Int]() for (index, element) in item.enumerated() { var singleObj = [String]() var singleGrid = [String]() var dictToAdd = [AnyHashable:Any]() if let type = element["type"] as? String{ if type == "txt"{ let id = element["id"] as? String ?? "" let imagePath = element["imagePath"] as? String ?? "" // let type = element["type"] as? String ?? "Text" var textTitle = element["title"] as? String ?? "" if textTitle == ""{ textTitle = "EmptyTitle" } var textSubTitle = element["description"] as? String ?? "" if textSubTitle == ""{ textSubTitle = "EmptySubTitle" } // let dw = element["dw"] as! String // let dh = element["dh"] as! String let height = element["height"] as? Int ?? 0 let width = element["width"] as? Int ?? 0 let txtSize = CGSize(width: SCREENWIDTH, height: CGFloat(height)) dictToAdd.updateValue(NSStringFromCGSize(txtSize), forKey: "original_size") let titleHeight = textTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: font!) let subtitle = textSubTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: subfont!) let total = CGFloat(80) + titleHeight + subtitle // txtSize.height = total // self.collectionArray[selectedIndex]["item_size"] = total // let original_size = CGSize(width: CGFloat((dw as NSString).floatValue), height: CGFloat((dh as NSString).floatValue)) var item_size = CGSize(width: SCREENWIDTH, height: CGFloat(200)) item_size.height = total dictToAdd.updateValue(id, forKey: "photo_id") dictToAdd.updateValue(imagePath, forKey: "item_url") dictToAdd.updateValue("Text", forKey: "type") let textAlignment = element["textAlignment"] as? Int ?? 1 dictToAdd.updateValue(textAlignment, forKey: "textAlignment") dictToAdd.updateValue("#322e20", forKey: "hexCode") //dictToAdd.updateValue(item_size, forKey: "original_size") dictToAdd.updateValue(item_size, forKey: "item_size") dictToAdd.updateValue(textTitle, forKey: "title") dictToAdd.updateValue(textSubTitle, forKey: "description") // dictToAdd.updateValue("xelpmoc story making processs", forKey: "textColor") dictToAdd.updateValue("#322e20", forKey: "textColor") let backgroundColor = element["backgroundColor"] as? String ?? "#FFFFFF" dictToAdd.updateValue(backgroundColor, forKey: "backgroundColor") singleObj.append("\(i)-\(leftCount)-\(0)") singleGrid.append(id) leftCount += 1 partitionGrid.append(singleGrid) partition.append(singleObj) // dictToAdd.updateValue(color, forKey: "hexCode") }else{ let below = element["below"] as! String if (below == ""){ search.updateValue(index, forKey: element["id"] as! String) let left = element["left"] as! Int if left == Int(0){ singleObj.append("\(i)-\(leftCount)-\(0)") singleGrid.append(element["id"] as! String) leftCount += 1 }else{ singleObj.append("\(i)-\(leftCount)-\(0)") singleGrid.append(element["id"] as! String) leftCount += 1 } partitionGrid.append(singleGrid) partition.append(singleObj) }else{ var index = "" // var indexToNest = id.index(of: below) var countLength = partition.count // var indexToInsert = search[below] belowCount += 1 var tempMiddle = leftCount - 1 partition[countLength-1].append("\(i)-\(tempMiddle)-\(belowCount)") } let id = element["id"] as? String ?? "" let imagePath = element["imagePath"] as? String ?? "" let type = element["type"] as? String ?? "" var dw = element["dw"] as? String ?? "" if dw == "undefined"{ dw = "0" } var dh = element["dh"] as? String ?? "" if dh == "undefined"{ dh = "0" } if let factor = element["factor"] as? AnyObject{ dictToAdd.updateValue("\(factor)", forKey: "factor") } if type != "video"{ let color = element["color"] as? String ?? "" dictToAdd.updateValue(color, forKey: "hexCode") } let height = element["height"] as? Int ?? 0 let width = element["width"] as? Int ?? 0 let original_size = CGSize(width: CGFloat((dw as NSString).floatValue), height: CGFloat((dh as NSString).floatValue)) let item_size = CGSize(width: CGFloat(width), height: CGFloat(height)) dictToAdd.updateValue(id, forKey: "photo_id") dictToAdd.updateValue(imagePath, forKey: "item_url") dictToAdd.updateValue(type, forKey: "type") dictToAdd.updateValue(original_size, forKey: "original_size") dictToAdd.updateValue(item_size, forKey: "item_size") // dictToAdd.updateValue(type, forKey: "type") } } self.collectionArray.append(dictToAdd) } localpartitionGrid.append(partitionGrid) localPartition.append(partition) i += 1 //partition.append(singleObj) } defaults.set(true, forKey: "isViewStory") defaults.set(localPartition, forKey: "partition") } //MARK: - Save Story func postStoryData(storyDataTosend:String) { var paramsDict = [String:String]() paramsDict.updateValue(storyId, forKey: "storyId") paramsDict.updateValue(self.storyTitle, forKey: "story_heading") paramsDict.updateValue(self.storySubtitle, forKey: "story_heading_description") paramsDict.updateValue("Chitaranjan", forKey: "writen_by") paramsDict.updateValue("CH", forKey: "writen_by_name_initials") paramsDict.updateValue("14946557868453", forKey: "writen_by_id") paramsDict.updateValue("chitaranjan", forKey: "writen_by_img") paramsDict.updateValue(story_cover_photo_path, forKey: "story_cover_photo_path") paramsDict.updateValue("#2b2b2a,#d2c6ad,#847f75,#9da29f,#6c86a2", forKey: "story_cover_photo_code") paramsDict.updateValue("#2b2b2a", forKey: "story_cover_photo_slice_code") paramsDict.updateValue(storyDataTosend, forKey: "storyJson") //print(paramsDict) // Params = Params + self.appendStroyIdAnddetails(Params: &paramsDict) //print(paramsDict) let pa = paramsDict as [String : Any] print(pa) var url = URLConstants.BaseURL + "addStory" Alamofire.request(url, method: .post, parameters: pa , encoding: URLEncoding.default, headers: nil) .validate() .responseJSON { (response:DataResponse<Any>) in print(response) switch response.result { case .success(let JSON): print("Success with JSON: \(JSON)") let response = JSON as! NSDictionary print("reee", response) let allKeys : NSArray = response.allKeys as NSArray; let tempVal : Bool = allKeys.contains("error") //retVal = [allKeys containsObject:key]; //return retVal; // if(response.key) if(tempVal == true){ let errorCode: AnyObject = response.value(forKeyPath: "error.errorCode") as! NSNumber let errorMSG = response.value(forKeyPath: "error.errorMsg") let compareCode: NSNumber = 0 if errorCode as! NSNumber == compareCode{ print("sucess") self.editTurnOn = false self.isViewStory = true } else { print("error") } }else{ print("error") AlertView.showAlert(self, title: "currently busy server", message: "Not reachable" as AnyObject) } case .failure(let error): print("Request failed with error: \(error)") AlertView.showAlert(self, title: "currently busy server", message: error as AnyObject) } } } func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) { let location = gestureReconizer.location(in: self.collectionView) switch gestureReconizer.state { case .began: if let local = defaults.object(forKey: "partition") as? partitionType{ localPartition = local } startDragAtLocation(location: location) break case .changed: guard let view = draggingView else { return } let cv = collectionView guard let originalIndexPath = originalIndexPath else {return} // view.center = CGPoint(x: location.x + dragOffset.x, y: location.y + dragOffset.y) var center = view.center center.x = location.x center.y = location.y view.center = center stopped = false scrollIfNeed(snapshotView: view) self.checkPreviousIndexPathAndCalculate(location: center, forScreenShort: view.frame, withSourceIndexPath: originalIndexPath) break case .ended: self.changeToIdentiPosition() editingTextFieldIndex = -1 self.editToolBar.isUserInteractionEnabled = true stopped = true endDragAtLocation(location: location) default: guard let view = draggingView else { return } var center = view.center center.y = location.y center.x = location.x view.center = center // break } } //MARK:- GestureRecognizer Methods func startDragAtLocation(location:CGPoint) { let vc = self.collectionView guard let indexPath = vc.indexPathForItem(at: location) else {return} guard let cell = vc.cellForItem(at: indexPath) else {return} self.sourceCell = cell if(selectedItemIndex != indexPath.item){ let previousSelected = selectedItemIndex selectedItemIndex = indexPath.item if previousSelected != -1{ self.collectionView.reloadItems(at: [IndexPath(item: previousSelected, section: 0)]) } } self.collectionView.performBatchUpdates({ self.collectionView.reloadData() }) { (test) in } self.editToolBar.isUserInteractionEnabled = false let selectedCell = collectionArray[indexPath.item] if let destType = selectedCell["type"] as? String { if destType == "Text"{ self.editToolbarConfigurationForTextCells() }else{ self.changeToEnrichMode() } } frameOfDragingIndexPath = cell.center originalIndexPath = indexPath draggingIndexPath = indexPath draggingView = cell.snapshotView(afterScreenUpdates: true) guard let view = draggingView else { return } view.frame = cell.frame print("center\(cell.center)") var center = cell.center view.center = CGPoint(x: center.x, y: location.y) vc.addSubview(view) view.layer.shadowPath = UIBezierPath(rect: (draggingView?.bounds)!).cgPath view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOpacity = 0.8 view.layer.shadowRadius = 10 view.alpha = 0.3 print("location \(location.y)") cell.alpha = 0.0 cell.isHidden = true UIView.animate(withDuration: 0.2, animations: { print("location \(location.y)") center.y = location.y view.center = CGPoint(x: location.x, y: location.y) if (cell.frame.size.height > SCREENHEIGHT * 0.75 || cell.frame.size.width > SCREENWIDTH * 0.8){ view.transform = CGAffineTransform(scaleX: 0.3, y: 0.3) }else{ view.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) } }) { (end) in } } func checkPreviousIndexPathAndCalculate(location:CGPoint,forScreenShort snapshot:CGRect,withSourceIndexPath sourceIndexPath:IndexPath){ self.changeToIdentiPosition() lineView.removeFromSuperview() self.swapView?.removeFromSuperview() var singletonArray = self.getSingletonArray() if let indexPath = self.collectionView.indexPathForItem(at: location){ guard var sourceCell = self.sourceCell else {return} if let destinationCell = self.collectionView.cellForItem(at: indexPath) { var destinationCellType = self.collectionArray[indexPath.item] var sourceCellType = self.collectionArray[sourceIndexPath.item] if indexPath.item != sourceIndexPath.item{ let topOffset = destinationCell.frame.origin.y + 25 let leftOffset = destinationCell.frame.origin.x + 25 let bottomOffset = destinationCell.frame.origin.y + destinationCell.frame.size.height - 25 let rightOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width - 25 let differenceLeft = location.x - leftOffset let differenceRight = location.x - rightOffset let differenceTop = location.y - topOffset let differenceBottom = location.y - bottomOffset var frmaes = defaults.object(forKey: "FramesForEachRow") as! [String] if let destType = destinationCellType["type"] as? String { if destType != "Text"{ guard let sourceType = sourceCellType["type"] as? String else { return } var keys = singletonArray[indexPath.item].components(separatedBy: "-") if differenceLeft > -25 && differenceLeft < 0 && sourceType != "Text"{ var cellFrame = CGRectFromString(frmaes[Int(keys[0])!]) print("Insert to the left of cell line") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() print("differenceLeft\(differenceLeft)") let xOffset = destinationCell.frame.origin.x print("\(xOffset)in left of the cell line ") let yValue = cellFrame.origin.y print("\(yValue)in left of the cell line ") let nestedWidth = 2.0 let nestedHeight = cellFrame.size.height self.collectionView.performBatchUpdates({ print("height destinationleft \(nestedHeight)") self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 0) }) // } }else if differenceRight < 25 && differenceRight > 0 && sourceType != "Text"{ var cellFrame = CGRectFromString(frmaes[Int(keys[0])!]) print("Insert to the right of the cell line") print("differenceright\(differenceRight)") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let xOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width let yValue = cellFrame.origin.y let nestedWidth = 2.0 let nestedHeight = cellFrame.size.height self.collectionView.performBatchUpdates({ print("height destinationright \(nestedHeight)") self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 0) }) }else if (differenceTop > -20 && differenceTop < 0 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the TOP of the cell line") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let xOffset = destinationCell.frame.origin.x let yValue = destinationCell.frame.origin.y let nestedWidth = destinationCell.frame.size.width let nestedHeight = 2.0 self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: CGFloat(nestedHeight)) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }) }else if(differenceBottom > 0 && differenceBottom < 20 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the Bottom of the cell line") lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let xOffset = destinationCell.frame.origin.x let yValue = destinationCell.frame.origin.y + destinationCell.frame.size.height + 2 let nestedWidth = destinationCell.frame.size.width let nestedHeight = 2.0 self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: CGFloat(nestedWidth), height: CGFloat(nestedHeight)) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) }, completion: { (test) in self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }) }else{ let dict = self.collectionArray[(originalIndexPath?.item)!] if let type = dict["type"] as? String{ if type != "Text"{ self.lineView.removeFromSuperview() self.swapView?.removeFromSuperview() self.collectionView.performBatchUpdates({ self.swapView?.frame = destinationCell.contentView.bounds self.swapView?.backgroundColor = UIColor.black self.swapView?.alpha = 0.6 self.swapImageView?.center = CGPoint(x: (self.swapView?.frame.size.width)! / 2, y: (self.swapView?.frame.size.height)! / 2) self.swapView?.addSubview(self.swapImageView!) destinationCell.contentView.addSubview(self.swapView!) }, completion: { (boolTest) in }) }else{ let delta: CGFloat = 0.00001 if abs(sourceCell.frame.size.width - destinationCell.frame.size.width) < delta { self.lineView.removeFromSuperview() self.swapView?.removeFromSuperview() self.collectionView.performBatchUpdates({ self.swapView?.frame = destinationCell.contentView.bounds self.swapView?.backgroundColor = UIColor.black self.swapView?.alpha = 0.6 self.swapImageView?.center = CGPoint(x: (self.swapView?.frame.size.width)! / 2, y: (self.swapView?.frame.size.height)! / 2) self.swapView?.addSubview(self.swapImageView!) destinationCell.contentView.addSubview(self.swapView!) }, completion: { (boolTest) in }) }else{ self.lineView.removeFromSuperview() } } } } }else{ if (sourceCell.frame.size.width == destinationCell.frame.size.width){ self.lineView.removeFromSuperview() self.swapView?.removeFromSuperview() self.collectionView.performBatchUpdates({ self.swapView?.frame = destinationCell.contentView.bounds self.swapView?.backgroundColor = UIColor.black self.swapView?.alpha = 0.6 self.swapImageView?.center = CGPoint(x: (self.swapView?.frame.size.width)! / 2, y: (self.swapView?.frame.size.height)! / 2) self.swapView?.addSubview(self.swapImageView!) destinationCell.contentView.addSubview(self.swapView!) }, completion: { (boolTest) in }) }else{ self.lineView.removeFromSuperview() } } } } else{ self.lineView.removeFromSuperview() print("outofsource") print("removed") // moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) } } }else{ let pIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x - 6, y: location.y)) let nIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x + 6, y: location.y)) let uIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y - 6)) let lIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y + 6)) var frmaes = defaults.object(forKey: "FramesForEachRow") as! [String] var sourceCellType = self.collectionArray[sourceIndexPath.item] guard let sourceType = sourceCellType["type"] as? String else { return } if var pIndexPath = pIndexPath,var nIndexPath = nIndexPath, sourceType != "Text"{ print("Insert in between two cells in the same row taken as horizontally line") var keys = singletonArray[pIndexPath.item].components(separatedBy: "-") if let pCell = self.collectionView.cellForItem(at:pIndexPath){ var cellFrame = CGRectFromString(frmaes[Int(keys[0])!]) self.lineView.removeFromSuperview() let xOffset = pCell.frame.origin.x + pCell.frame.size.width let yValue = cellFrame.origin.y let nestedHeight = cellFrame.size.height let nestedWidth = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 0) }, completion: { (bool) in }) } }else if var uIndexPath = uIndexPath,var lIndexPath = lIndexPath{ print("Insert in between two cells in the same row taken as vertically line") if let uCell = self.collectionView.cellForItem(at:uIndexPath){ var uKey = singletonArray[uIndexPath.item].components(separatedBy: "-") var lKey = singletonArray[lIndexPath.item].components(separatedBy: "-") var cellFrame = CGRectFromString(frmaes[Int(uKey[0])!]) if Int(uKey[0]) == Int(lKey[0]) { if sourceType != "Text"{ let xOffset = uCell.frame.origin.x let yValue = uCell.frame.origin.y + uCell.frame.size.height + 2 let nestedWidth = uCell.frame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) }else{ self.lineView.removeFromSuperview() } }else{ print("Different row") let xOffset = cellFrame.origin.x let yValue = uCell.frame.origin.y + uCell.frame.size.height + 3 let nestedWidth = cellFrame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) } } }else if var uIndexPath = uIndexPath , lIndexPath == nil{ var uKey = singletonArray[uIndexPath.item].components(separatedBy: "-") if ((Int(uKey[0])!) == localPartition.count - 1) { print("insert at the bottom of collection view line") let cellFrame = CGRectFromString(frmaes[Int(uKey[0])!]) let xOffset = cellFrame.origin.x let yValue = cellFrame.origin.y + cellFrame.size.height + 3 let nestedWidth = cellFrame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) }else{ self.lineView.removeFromSuperview() } }else if var lIndexPath = lIndexPath , uIndexPath == nil{ var lKey = singletonArray[lIndexPath.item].components(separatedBy: "-") if ((Int(lKey[0])!) == 0) { print("Insert at the top of collection view line") let cellFrame = CGRectFromString(frmaes[Int(lKey[0])!]) let xOffset = cellFrame.origin.x let yValue = cellFrame.origin.y let nestedWidth = cellFrame.size.width let nestedHeight = CGFloat(2.0) self.collectionView.performBatchUpdates({ self.lineView.frame = CGRect(x: xOffset, y: yValue, width: nestedWidth, height: nestedHeight) self.lineView.backgroundColor = UIColor.black self.collectionView.addSubview(self.lineView) self.moveCellsApartWithFrame(frame: (self.lineView.frame), andOrientation: 1) }, completion: { (bool) in }) }else{ self.lineView.removeFromSuperview() } }else{ print("move snapshot to its original position line") self.lineView.removeFromSuperview() } } } func endDragAtLocation(location:CGPoint){ let vc = collectionView guard let originalIndexPath = originalIndexPath else {return} guard var dragView = self.draggingView else {return} guard var cell = self.sourceCell else {return} if let indexPath = vc.indexPathForItem(at: location),let destination = vc.cellForItem(at: indexPath) { //added if let indexPath = vc.indexPathForItem(at: location){ let sourceCell = vc.cellForItem(at: originalIndexPath) if let destinationCell = vc.cellForItem(at: indexPath) { self.changeToIdentiPosition() lineView.removeFromSuperview() self.swapView?.removeFromSuperview() // print("\(indexPath.item)source but destination\(sourceIndexPath.item)") if indexPath.item != originalIndexPath.item{ let dict = self.collectionArray[originalIndexPath.item] if let type = dict["type"] as? String{ if type != "Text"{ let topOffset = destinationCell.frame.origin.y + 20 let leftOffset = destinationCell.frame.origin.x + 20 let bottomOffset = destinationCell.frame.origin.y + destinationCell.frame.size.height - 20 let rightOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width - 20 let differenceLeft = location.x - leftOffset let differenceRight = location.x - rightOffset // print("destination\(destinationCell.frame)") let differenceTop = location.y - topOffset let differenceBottom = location.y - bottomOffset if differenceLeft > -20 && differenceLeft < 0 { print("Insert to the left of cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) sourceCell?.isHidden = false // originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() // dragView = nil //[snapshot removeFromSuperview]; //snapshot = nil; }else if differenceRight < 20 && differenceRight > 0{ print("Insert to the right of the cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) sourceCell?.isHidden = false // originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() // dragView = nil // need to remove top should be uncomment }else if (differenceTop > -20 && differenceTop < 0 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16)){ print("Insert to the TOP of the cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) sourceCell?.isHidden = false // originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() //self.draggingView = nil }else if(differenceBottom > 0 && differenceBottom < 20 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16)){ print("Insert to the Bottom of the cell line") self.insertNewCellAtPoint(location: location, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: (self.draggingView?.frame)!) sourceCell?.isHidden = false //originalIndexPath = nil sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() //self.draggingView = nil }else{ let dict = self.collectionArray[(indexPath.item)] if let type = dict["type"] as? String{ if type != "Text"{ self.exchangeDataSource(sourceIndex: indexPath.item, destIndex: (self.originalIndexPath?.item)!) vc.performBatchUpdates({ // print("\(UserDefaults.standard.object(forKey: "partition"))final partation") self.collectionView.moveItem(at: self.originalIndexPath!, to: indexPath) self.collectionView.moveItem(at: indexPath, to: self.originalIndexPath!) }, completion: { (Bool) in UIView.animate(withDuration: 0.2, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 }, completion: { (end) in self.draggingView!.alpha = 0.0 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) // // cell.alpha = 1 // cell.isHidden = false // dragView.removeFromSuperview() // // vc.layoutIfNeeded() // // vc.setNeedsLayout() // self.originalIndexPath = nil // self.draggingView = nil }) }else{ let delta: CGFloat = 0.00001 if abs(cell.frame.size.width - destinationCell.frame.size.width) < delta { self.exchangeDataSource(sourceIndex: indexPath.item, destIndex: (self.originalIndexPath?.item)!) self.selectedItemIndex = indexPath.item vc.performBatchUpdates({ self.collectionView.moveItem(at: self.originalIndexPath!, to: indexPath) self.collectionView.moveItem(at: indexPath, to: self.originalIndexPath!) }, completion: { (Bool) in UIView.animate(withDuration: 0.2, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 }, completion: { (end) in self.draggingView!.alpha = 0.0 cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) // cell.alpha = 1 // cell.isHidden = false // dragView.removeFromSuperview() // self.originalIndexPath = nil // self.draggingView = nil }) }else{ self.lineView.removeFromSuperview() cell.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 }, completion: { (end) in self.draggingView!.alpha = 0.0 cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) } } } } }else{ //Swap the images let delta: CGFloat = 0.00001 if abs(cell.frame.size.width - destinationCell.frame.size.width) < delta { self.exchangeDataSource(sourceIndex: indexPath.item, destIndex: (self.originalIndexPath?.item)!) self.selectedItemIndex = indexPath.item vc.performBatchUpdates({ self.collectionView.moveItem(at: self.originalIndexPath!, to: indexPath) self.collectionView.moveItem(at: indexPath, to: self.originalIndexPath!) }, completion: { (Bool) in UIView.animate(withDuration: 0.2, animations: { dragView.frame = cell.frame dragView.alpha = 1 }, completion: { (end) in dragView.alpha = 0.0 cell.alpha = 1 cell.isHidden = false dragView.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil // dragView = nil }) // cell.alpha = 1 // cell.isHidden = false // dragView.removeFromSuperview() // self.originalIndexPath = nil // self.draggingView = nil }) }else{ self.lineView.removeFromSuperview() cell.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1.0 }, completion: { (end) in cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) } } } } else{ print("testign not visible") print("outofsource") self.lineView.removeFromSuperview() // cell.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.draggingView!.frame = cell.frame self.draggingView!.alpha = 1 // cell.alpha = 1 }, completion: { (end) in cell.alpha = 1 cell.isHidden = false self.draggingView?.removeFromSuperview() self.collectionView.layoutIfNeeded() self.collectionView.setNeedsLayout() // cell.alpha = 1 self.originalIndexPath = nil self.draggingView = nil }) } } } }else{ self.changeToIdentiPosition() lineView.removeFromSuperview() self.swapView?.removeFromSuperview() let pIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x - 6, y: location.y)) let nIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x + 6, y: location.y)) let uIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y - 6)) let lIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y + 6)) // guard let indexPath = vc.indexPathForItem(at: location)else{ return } let dict = self.collectionArray[originalIndexPath.item] let type = dict["type"] as! String if var pIndexPath = pIndexPath,var nIndexPath = nIndexPath,type != "Text"{ let dict = self.collectionArray[(originalIndexPath.item)] if let type = dict["type"] as? String{ if type != "Text"{ print("Insert in between two cells in the same row taken as horizontally gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 dragView.removeFromSuperview() } } }else if var uIndexPath = uIndexPath,var lIndexPath = lIndexPath{ // let dict = self.collectionArray[(originalIndexPath.item)] print("Insert in between two cells in the same row taken as vertically gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 // originalIndexPath = nil //sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() }else if var uIndexPath = uIndexPath, lIndexPath == nil{ print("insert at the bottom of collection view gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 //originalIndexPath = nil //sourceCell?.removeFromSuperview() //sourceCell.hidden = NO; //sourceIndexPath = nil; dragView.removeFromSuperview() } else if var lIndexPath = lIndexPath, uIndexPath == nil{ print("insert at the top of collection view gesture") self.insertNewCellAtPoint(location: dragView.center, withSourceIndexPathwithSourceIndexPath: originalIndexPath, forSnapshot: dragView.frame) let sourceCell = vc.cellForItem(at: originalIndexPath) sourceCell?.isHidden = false sourceCell?.alpha = 1 // originalIndexPath = nil dragView.removeFromSuperview() }else{ self.lineView.removeFromSuperview() guard var frameOfDraging = self.frameOfDragingIndexPath else { return } guard var sourceCell = self.sourceCell else {return} // guard let sourceCell = self.collectionView.cellForItem(at:originalIndexPath)else { return } UIView.animate(withDuration: 0.25, animations: { dragView.center = frameOfDraging dragView.transform = CGAffineTransform.identity dragView.alpha = 0.0; sourceCell.alpha = 1.0; }, completion: { (flag) in sourceCell.isHidden = false self.originalIndexPath = nil dragView.removeFromSuperview() }) } } } func scrollIfNeed(snapshotView:UIView) { var cellCenter = snapshotView.center var newOffset = collectionView.contentOffset let buffer = CGFloat(10) let bottomY = collectionView.contentOffset.y + collectionView.frame.size.height - 100 // print("bottomY\(bottomY)") //print("(snapshotView.frame.maxY - buffer)\((snapshotView.frame.maxY - buffer))") //print("condition \(bottomY < (snapshotView.frame.maxY - buffer))") if (bottomY < (snapshotView.frame.maxY - buffer)){ newOffset.y = newOffset.y + 1 // print("uppppp") if (((newOffset.y) + (collectionView.bounds.size.height)) > (collectionView.contentSize.height)) { return } cellCenter.y = cellCenter.y + 1 } let offsetY = collectionView.contentOffset.y // print("chita \(offsetY)") if (snapshotView.frame.minY + buffer < offsetY) { // print("Atul\(snapshotView.frame.minY + buffer)") // We're scrolling up newOffset.y = newOffset.y - 1 // print("downnnn") if ((newOffset.y) <= CGFloat(0)) { return } // adjust cell's center by 1 cellCenter.y = cellCenter.y - 1 } collectionView.contentOffset = newOffset snapshotView.center = cellCenter; // Repeat until we went to far. if(self.stopped == true){ return }else { let deadlineTime = DispatchTime.now() + 0.3 DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: { self.scrollIfNeed(snapshotView: snapshotView) }) } } func autoScroll() { if self.collectionArray.count > 1{ self.collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .centeredVertically, animated: true) } } func autoScrollToTop() { if let headerAttributes = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)){ self.collectionView.setContentOffset(CGPoint(x: 0, y: (headerAttributes.frame.origin.x)), animated: true) } } //MARK :- Supplementary DataSource func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { if reloadHeaderView == true{ headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) as? PictureHeaderCollectionReusableView headerView?.delegate = self self.headerView?.iboTitle.delegate = self self.headerView?.iboSubTitle.delegate = self if isLoadingStory{ self.barButtonActivityIndicator.startAnimating() self.headerView?.iboScrollDownBrn.setImage(nil, for: .normal) self.headerView?.iboScrollDownBrn.addSubview(barButtonActivityIndicator) }else{ self.barButtonActivityIndicator.stopAnimating() barButtonActivityIndicator.removeFromSuperview() self.headerView?.iboScrollDownBrn.setImage(UIImage(named: "down"), for: .normal) UIView.animate(withDuration: 0.3, animations: { self.headerView?.iboScrollDownBrn.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) }, completion: { _ in UIView.animate(withDuration: 0.3) { self.headerView?.iboScrollDownBrn.transform = CGAffineTransform.identity } }) } if self.isViewStory{ headerView?.iboHeaderImage.removeGestureRecognizer(singleTap) self.headerView?.iboHeaderImage.backgroundColor = UIColor(hexString: self.story_cover_photo_slice_code) var urlImage = self.story_cover_photo_path.components(separatedBy: "album") self.headerView?.iboTitle.text = self.storyTitle self.headerView?.iboSubTitle.text = self.storySubtitle self.headerView?.iboTitle.isUserInteractionEnabled = false self.headerView?.iboSubTitle.isUserInteractionEnabled = false var totalPath = URLConstants.imgDomain if let data = coverdata { //self.headerView?.iboHeaderImage.contentMode = UIViewContentMode.scaleAspectFill DispatchQueue.main.async { self.headerView?.iboHeaderImage.image = data } }else { self.headerView?.iboHeaderImage.sd_setImage(with: URL(string: totalPath + urlImage[1]), placeholderImage: UIImage(named: ""), options: SDWebImageOptions.progressiveDownload, completed: { (image, data, error, finished) in guard let image = image else { return } print("Image loaded!") self.headerView?.iboHeaderImage.contentMode = UIViewContentMode.scaleAspectFill self.headerView?.iboHeaderImage.image = image self.coverdata = image // self.iboProfileLoaderIndicator.stopAnimating() }) } }else{ if isFirstTime { self.perform(#selector(checkForHeaderTitle), with: nil, afterDelay: 0.5) } self.headerView?.iboTitle.isUserInteractionEnabled = true self.headerView?.iboSubTitle.isUserInteractionEnabled = true headerView?.iboHeaderImage.addGestureRecognizer(singleTap) if let coverData = coverdata{ self.headerView?.iboHeaderImage.image = coverData } } } return headerView! } else if kind == UICollectionElementKindSectionFooter { // assert(0) let fotterView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FotterView", for: indexPath) as! FooterReusableView fotterView.iboOwnerImg.setImage(string: "Chitaranjan sahu", color: UIColor(hexString:"#7FC9F1"), circular: true) fotterView.delegate = self fotterView.backgroundColor = UIColor.white return fotterView }else{ return UICollectionReusableView() } } func checkForHeaderTitle() { if isFirstTime { self.headerView?.iboTitle.becomeFirstResponder() self.isFirstTime = false } } func sameRowOrNot(sourceIndexPath: Int,destinationIndexPath :Int ) -> Bool { var singletonArray = self.getSingletonArray() let destPaths = singletonArray[sourceIndexPath] let sourcePaths = singletonArray[destinationIndexPath] var destKeys = destPaths.components(separatedBy: "-") var sourceKeys = destPaths.components(separatedBy: "-") if destKeys[0] == sourceKeys[0]{ return true }else{ return false } } func moveCellsApartWithFrame(frame:CGRect,andOrientation orientation:Int) { var certOne = CGRect.zero var certTwo = CGRect.zero cellsToMove0.removeAllObjects() cellsToMove1.removeAllObjects() if orientation == 0 { certOne = CGRect(x: frame.origin.x, y: frame.origin.y, width: CGFloat.greatestFiniteMagnitude, height: frame.size.height) certTwo = CGRect(x: 0.0, y: frame.origin.y, width: frame.origin.x, height: frame.size.height) print("\(certOne)first One") print("\(certTwo)secondOne") }else{ certOne = CGRect(x: frame.origin.x, y: frame.origin.y, width: CGFloat.greatestFiniteMagnitude, height: frame.size.height) certTwo = CGRect(x: frame.origin.x, y: 0.0, width: frame.size.width, height: frame.origin.y) } for i in 0 ..< self.collectionArray.count{ let indexPath = IndexPath(item: i, section: 0) if let cell = self.collectionView.cellForItem(at: indexPath){ if (cell.frame.intersects(certOne)){ cellsToMove0.add(cell) }else if (cell.frame.intersects(certTwo)) { cellsToMove1.add(cell) } } } self.collectionView.performBatchUpdates({ for i in 0 ..< self.cellsToMove0.count{ if orientation == 0{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove0[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: 5.0, y: 0.0) }) }else{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove0[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: 0.0, y: 5.0) }) } } for i in 0 ..< self.cellsToMove1.count{ if orientation == 0{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove1[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: -5.0, y: 0.0) }) }else{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove1[i] as! UICollectionViewCell cell.transform = CGAffineTransform(translationX: 0.0, y: -5.0) }) } } }, completion: { (Bool) in }) } func changeToIdentiPosition() { self.collectionView.performBatchUpdates({ for i in 0 ..< self.cellsToMove0.count{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove0[i] as! UICollectionViewCell cell.transform = CGAffineTransform.identity }) } for i in 0 ..< self.cellsToMove1.count{ UIView.animate(withDuration: 0.2, animations: { let cell = self.cellsToMove1[i] as! UICollectionViewCell cell.transform = CGAffineTransform.identity }) } }, completion: { (test) in }) } func cancelClicked() { self.defaults.removeObject(forKey: "isViewStory") if upload{ self.navigationController?.dismiss(animated: true, completion: nil) self.upload = false }else{ _ = self.navigationController?.popViewController(animated: true) } } func insertNewCellAtPoint(location:CGPoint ,withSourceIndexPathwithSourceIndexPath sourceIndexPath : IndexPath ,forSnapshot snapshot:CGRect){ if let destinationIndexPath = self.collectionView.indexPathForItem(at: location){ if let destinationCell = self.collectionView.cellForItem(at: destinationIndexPath){ let temp = collectionArray[destinationIndexPath.row] let source = collectionArray[sourceIndexPath.row] let type = temp["type"] as! String let sourceType = source["type"] as! String if destinationIndexPath.item != sourceIndexPath.item{ if (type != "Text") { let topOffset = destinationCell.frame.origin.y + 20 let leftOffset = destinationCell.frame.origin.x + 20 let bottomOffset = destinationCell.frame.origin.y + destinationCell.frame.size.height - 20 let rightOffset = destinationCell.frame.origin.x + destinationCell.frame.size.width - 20 let differenceLeft = location.x - leftOffset let differenceRight = location.x - rightOffset let differenceTop = location.y - topOffset let differenceBottom = location.y - bottomOffset var singletonArray = self.getSingletonArray() var sourseKey = singletonArray[sourceIndexPath.item] var sourseKeys = sourseKey.components(separatedBy: "-") // if let sourseKeys = findWithIndex(array: singletonArray, index: sourceIndexPath.item){ if(differenceLeft > -20 && differenceLeft < 0 && sourceType != "Text"){ print("Inserting to the left of cell") let destPaths = singletonArray[destinationIndexPath.item] // let destPaths = findWithIndex(array: singletonArray, index: destinationIndexPath.item) var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] //let rowNumber :NSArray = self.localPartition.object(at: Int(destKeys[0])!) as! NSArray // let rowNumber : NSMutableArray = self.localPartition.object(at: destKeys[0]) let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.first var destIndex = singletonArray.index(of: searchString!) if sourceIndexPath.item < destinationIndexPath.item && destIndex != 0{ destIndex = destIndex! - 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var insertRowArray = insertRow let columnNumber = Int((destKeys[1]))! guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(0)" var arrayObj = [ArrayWithObj] //var arrayObj = NSArray(array: [ArrayWithObj]) // arrayObj.adding(ArrayWithObj) // arrayObj.append(ArrayWithObj) insertRowArray.insert(arrayObj, at: columnNumber) print("start\(insertRowArray)") for i in columnNumber ..< insertRowArray.count{ var insertColumn = insertRowArray[i] // let insertColumnArray = [insertColumn] // let insertColumnArray = NSMutableArray.init(array: [insertColumn]) print("start\(insertColumn)") for j in 0 ..< insertColumn.count{ insertColumn[j] = "\(newIndex)-\(i)-\(j)" // insertColumnArray.replaceObject(at: j, with: "\(newIndex)-\(i)-\(j)") } insertRowArray[i] = insertColumn } self.localPartition[newIndex] = insertRowArray print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) print("locacl Part") let sourseKeysSecond = Int(sourseKeys[1])! + 1 if (Int(sourseKeys[0])) == Int(destKeys[0]){ if (Int(sourseKeys[1]) )! >= Int(destKeys[1])!{ sourseKeys[0] = "\(Int(sourseKeys[0])!)" sourseKeys[1] = "\(sourseKeysSecond)" sourseKeys[2] = "\(Int(sourseKeys[2])!)" } } let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ // UIView.setAnimationsEnabled(false) self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // UIView.setAnimationsEnabled(true) // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) }else if (differenceRight < 20 && differenceRight > 0 && sourceType != "Text"){ print("Inserting to the right of cell") let destPaths = singletonArray[destinationIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.last var destIndex = singletonArray.index(of: searchString!) let columnNumber = Int((destKeys[1]))! + 1 destKeys[0] = destKeys[0] destKeys[1] = "\(columnNumber)" destKeys[2] = destKeys[2] if sourceIndexPath.item > destIndex!{ destIndex = destIndex! + 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var insertRowArray = insertRow guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(0)" var arrayObj = [ArrayWithObj] //var arrayObj = NSArray(array: [ArrayWithObj]) // arrayObj.adding(ArrayWithObj) // arrayObj.append(ArrayWithObj) insertRowArray.insert(arrayObj, at: columnNumber) print("start\(insertRowArray)") for i in columnNumber ..< insertRowArray.count{ var insertColumn = insertRowArray[i] // let insertColumnArray = [insertColumn] // let insertColumnArray = NSMutableArray.init(array: [insertColumn]) print("start\(insertColumn)") for j in 0 ..< insertColumn.count{ insertColumn[j] = "\(newIndex)-\(i)-\(j)" // insertColumnArray.replaceObject(at: j, with: "\(newIndex)-\(i)-\(j)") } insertRowArray[i] = insertColumn } self.localPartition[newIndex] = insertRowArray print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! print("locacl Part") let sourseKeysSecond = Int(sourseKeys[1])! + 1 if (Int(sourseKeys[0])) == Int(destKeys[0]){ if (Int(sourseKeys[1]) )! >= Int(destKeys[1])!{ sourseKeys[0] = "\(Int(sourseKeys[0])!)" sourseKeys[1] = "\(sourseKeysSecond)" sourseKeys[2] = "\(Int(sourseKeys[2])!)" //sourseKeys = ["\(Int(sourseKeys[0])!)-\(sourseKeysSecond)-\(Int(sourseKeys[2])!)"] } } let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) }else if (differenceTop > -20 && differenceTop < 0 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the top of that cell") let destPaths = singletonArray[destinationIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destIndex = destinationIndexPath.item if sourceIndexPath.item < destIndex { destIndex = destIndex - 1 } var destRowArray = self.localPartition[Int(destKeys[0])!] var destColArray = destRowArray[Int(destKeys[1])!] // let searchString = nextItem.first var newObj = destKeys[0] + "-" + destKeys[1] + "-" + "\(destColArray.count)" destColArray.append(newObj) destRowArray[Int(destKeys[1])!] = destColArray localPartition[Int(destKeys[0])!] = destRowArray let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) var rowArray = self.localPartition[(Int(sourseKeys[0]))!] var columnArray = rowArray[(Int(sourseKeys[1]))!] print("column array \(columnArray)") columnArray.remove(at: columnArray.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &rowArray , andColumn: &columnArray, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else if(differenceBottom > 0 && differenceBottom < 20 && destinationCell.frame.size.width < (UIScreen.main.bounds.width - 16) && sourceType != "Text"){ print("Insert to the bottom of that cell") let destPaths = singletonArray[destinationIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destRowArray = self.localPartition[Int(destKeys[0])!] var destIndex = destinationIndexPath.item if sourceIndexPath.item > destIndex { destIndex = destIndex + 1 } var destColArray = destRowArray[Int(destKeys[1])!] // let searchString = nextItem.first var newObj = destKeys[0] + "-" + destKeys[1] + "-" + "\(destColArray.count)" destColArray.append(newObj) destRowArray[Int(destKeys[1])!] = destColArray localPartition[Int(destKeys[0])!] = destRowArray let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) var rowArray = self.localPartition[(Int(sourseKeys[0]))!] var columnArray = rowArray[(Int(sourseKeys[1]))!] print("column array \(columnArray)") columnArray.remove(at: columnArray.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &rowArray , andColumn: &columnArray, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else{ self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } }else{ self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } }else{ self.lineView.removeFromSuperview() } } }else{ let pIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x - 6, y: location.y)) let nIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x + 6, y: location.y)) let uIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y - 6)) let lIndexPath = self.collectionView.indexPathForItem(at: CGPoint(x: location.x, y: location.y + 6)) //guard let indexPath = self.collectionView?.indexPathForItem(at: location)else{ return } var singletonArray = self.getSingletonArray() var sourseKey = singletonArray[sourceIndexPath.item] var sourseKeys = sourseKey.components(separatedBy: "-") let temp = collectionArray[sourceIndexPath.row] let type = temp["type"] as! String if var pIndexPath = pIndexPath,var nIndexPath = nIndexPath, type != "Text"{ let dict = self.collectionArray[sourceIndexPath.item] if let type = dict["type"] as? String{ if type != "Text"{ print("Insert in between two cells in the same row taken as horizontally") print("Inserting to the right of cell") let destPaths = singletonArray[pIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.first // let nextItem = rowNumber.object(at: destKeys[1]) var destIndex = singletonArray.index(of: searchString!) if sourceIndexPath.item > destIndex!{ destIndex = destIndex! + 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var insertRowArray = insertRow let columnNumber = Int((destKeys[1]))! guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(0)" var arrayObj = [ArrayWithObj] //var arrayObj = NSArray(array: [ArrayWithObj]) // arrayObj.adding(ArrayWithObj) // arrayObj.append(ArrayWithObj) insertRowArray.insert(arrayObj, at: columnNumber) print("start\(insertRowArray)") for i in columnNumber ..< insertRowArray.count{ var insertColumn = insertRowArray[i] // let insertColumnArray = [insertColumn] // let insertColumnArray = NSMutableArray.init(array: [insertColumn]) print("start\(insertColumn)") for j in 0 ..< insertColumn.count{ insertColumn[j] = "\(newIndex)-\(i)-\(j)" // insertColumnArray.replaceObject(at: j, with: "\(newIndex)-\(i)-\(j)") } insertRowArray[i] = insertColumn } self.localPartition[newIndex] = insertRowArray print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! print("locacl Part") let sourseKeysSecond = Int(sourseKeys[1])! + 1 if (Int(sourseKeys[0])) == Int(destKeys[0]){ if (Int(sourseKeys[1]) )! >= Int(destKeys[1])!{ sourseKeys[0] = "\(Int(sourseKeys[0])!)" sourseKeys[1] = "\(sourseKeysSecond)" sourseKeys[2] = "\(Int(sourseKeys[2])!)" //sourseKeys = ["\(Int(sourseKeys[0])!)-\(sourseKeysSecond)-\(Int(sourseKeys[2])!)"] } } let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) } } }else if var uIndexPath = uIndexPath,var lIndexPath = lIndexPath{ print("Insert in between two cells in the same row taken as vertically line") if let uCell = self.collectionView.cellForItem(at:uIndexPath){ var uKey = singletonArray[uIndexPath.item].components(separatedBy: "-") var lKey = singletonArray[lIndexPath.item].components(separatedBy: "-") // var cellFrame = CGRectFromString(frmaes[Int(uKey[0])!]) if Int(uKey[0]) == Int(lKey[0]) { let dict = self.collectionArray[sourceIndexPath.item] if let type = dict["type"] as? String{ if type != "Text"{ print("Inserting to the right of cell") let destPaths = singletonArray[uIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") let rowNumber = self.localPartition[Int(destKeys[0])!] let rowTemp = rowNumber let nextItem = rowTemp[Int(destKeys[1])!] let searchString = nextItem.first // let nextItem = rowNumber.object(at: destKeys[1]) var destIndex = singletonArray.index(of: searchString!) if sourceIndexPath.item > destIndex!{ destIndex = destIndex! + 1 } var insertRow = self.localPartition[Int((destKeys[0]))!] var destColArray = insertRow[Int((destKeys[1]))!] let columnNumber = Int((destKeys[1]))! guard let newIndex = Int(destKeys.first!) else { return } print("New index \(newIndex)") let ArrayWithObj = "\(newIndex)-\(columnNumber)-\(destColArray.count)" destColArray.append(ArrayWithObj) insertRow[columnNumber] = destColArray self.localPartition[Int((destKeys[0]))!] = insertRow let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) }else{ self.reloadHeaderView = false self.lineView.removeFromSuperview() let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } } }else{ print("Different row") let destPaths = singletonArray[uIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var lastItem = self.localPartition[Int(destKeys[0])!] var nested = lastItem.last var thirdNested = nested?.last var destIndex = singletonArray.index(of: thirdNested!) destIndex! = destIndex! + 1 if sourceIndexPath.item < destIndex!{ destIndex = destIndex! - 1 } var destRow = Int(destKeys.first!)! + 1 var newObj = ["\(destRow)-0-0"] var insertObj = [newObj] self.localPartition.insert(insertObj, at: destRow) // self.localPartition[destRow] = insertObj for i in (destRow + 1) ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } self.localPartition[i] = rowArray } let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex!) selectedItemIndex = destIndex! var sourceRow = (Int(sourseKeys[0]))! if(destRow <= sourceRow){ sourceRow = sourceRow + 1 } sourseKeys[0] = "\(sourceRow)" sourseKeys[1] = sourseKeys[1] sourseKeys[2] = sourseKeys[2] //sourseKeys = ["\(sourceRow)",sourseKeys[1],sourseKeys[2]] var rowArray = self.localPartition[sourceRow] var columnArray = rowArray[(Int(sourseKeys[1]))!] print("column array \(columnArray)") columnArray.remove(at: columnArray.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &rowArray , andColumn: &columnArray, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex!, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex!, section: 0), at: .centeredVertically, animated: true) }) } } }else if var uIndexPath = uIndexPath, lIndexPath == nil{ var uKey = singletonArray[uIndexPath.item] var uKey1 = uKey.components(separatedBy: "-") if Int(uKey1[0])! == (self.localPartition.count - 1){ print("insert at the bottom of collection view") var destPaths = singletonArray[uIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destIndex = singletonArray.count - 1 var destRow = Int(destKeys.first!)! + 1 var newObj = ["\(destRow)-0-0"] var insertObj = [newObj] self.localPartition.insert(insertObj, at: destRow) // self.localPartition[destRow] = insertObj for i in destRow+1 ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } localPartition[i] = rowArray } // self.localPartition[newIndex] = insertRowArray // print("NEW Index\(destIndex)") let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) print("locacl Part") let rowArray = self.localPartition[(Int(sourseKeys[0]))!] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else{ self.lineView.removeFromSuperview() var indexSet :IndexSet = [0] self.collectionView.reloadSections(indexSet) } }else if var lIndexPath = lIndexPath, uIndexPath == nil { var lKey = singletonArray[lIndexPath.item] var lKey1 = lKey.components(separatedBy: "-") if( Int(lKey1[0])! == 0) { print("Insert at the top of collection view") var destPaths = singletonArray[lIndexPath.item] var destKeys = destPaths.components(separatedBy: "-") var destIndex = 0 var destRow = Int(destKeys.first!)! var newObj = ["\(destRow)-0-0"] var insertObj = [newObj] self.localPartition.insert(insertObj, at: destRow) // self.localPartition[destRow] = insertObj for i in destRow+1 ..< self.localPartition.count{ var rowArray = self.localPartition[i] for j in 0 ..< rowArray.count{ var colArray = rowArray[j] for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" } rowArray[j] = colArray } localPartition[i] = rowArray } let obj = collectionArray[sourceIndexPath.item] collectionArray.remove(at: sourceIndexPath.item) collectionArray.insert(obj, at: destIndex) print("locacl Part") selectedItemIndex = destIndex var sourceRow = Int(sourseKeys[0])! if(destRow <= sourceRow){ sourceRow = sourceRow + 1 } sourseKeys[0] = "\(sourceRow)" sourseKeys[1] = sourseKeys[1] sourseKeys[2] = sourseKeys[2] let rowArray = self.localPartition[(Int(sourceRow))] // let rowArray = (self.localPartition.object(at: (Int(sourseKeys[0]))!) as! NSArray) var row = rowArray print("source row array\(row)") let columnArray = row[(Int(sourseKeys[1]))!] // let columnArray = row.object(at: (Int(sourseKeys[1]))!) as! NSArray var column = columnArray print("column array \(column)") column.remove(at: column.count-1) // need uncomment Code self.changePartitionForSourceRowWithRow(rowArray: &row , andColumn: &column, andSourceKeys: &sourseKeys , andDestKeys: &destKeys) defaults.set(localPartition, forKey: "partition") if let local = defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ print(local) } self.collectionView.performBatchUpdates({ self.collectionView.moveItem(at: sourceIndexPath, to: IndexPath(item: destIndex, section: 0)) }, completion: { (bool) in self.reloadHeaderView = false let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() // self.collectionView?.scrollToItem(at: IndexPath(item: destIndex, section: 0), at: .centeredVertically, animated: true) }) }else{ self.reloadHeaderView = false self.lineView.removeFromSuperview() let set :IndexSet = [0] CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.reloadSections(set) CATransaction.commit() } }else{ self.lineView.removeFromSuperview() } } self.changeToIdentiPosition() } func changePartitionForSourceRowWithRow(rowArray :inout Array<Array<String>>,andColumn columnArray:inout Array<String>,andSourceKeys keys: inout Array<String>,andDestKeys destKeys:inout Array<String>) { if (columnArray.count > 0){ //rowArray[Int(keys[1])!] = columnArray rowArray[Int(keys[1])!] = columnArray // rowArray.replaceObject(at: Int(keys[1] as! String)! , with: columnArray) localPartition[Int(keys[0])!] = rowArray // localPartition.replaceObject(at:Int(keys[0] as! String)!, with: rowArray) }else{ rowArray.remove(at: Int(keys[1])!) // rowArray.removeObject(at: keys[1] as! Int) if rowArray.count != 0{ if rowArray.count == 1 && (rowArray[0].count > 1){ localPartition.remove(at: Int(keys[0])!) let sourceRow = Int(keys[0])! let rowCount = rowArray[0].count for i in sourceRow..<(sourceRow + rowCount) { let ArrayWithObj = "\(i)-\(0)-\(0)" var arrayObj = [ArrayWithObj] let rowObject = [arrayObj] localPartition.insert(rowObject, at: i) //localPartition.insert(rowObject, at: i) } for j in (sourceRow+rowCount) ..< localPartition.count{ var rowArray = localPartition[j] //let rowArray : NSMutableArray = localPartition.object(at: j) as! NSMutableArray for k in 0 ..< rowArray.count{ var colArray1 = rowArray[k] //let colArray1:NSMutableArray = rowArray.object(at: k) as! NSMutableArray for l in 0 ..< colArray1.count{ colArray1[l] = "\(j)-\(k)-\(l)" //colArray1.replaceObject(at: l, with: "\(j)-\(k)-\(l)") } rowArray[k] = colArray1 //rowArray.replaceObject(at: k, with: colArray1) } localPartition[j] = rowArray //localPartition.replaceObject(at: j, with: rowArray) } }else{ for i in Int(keys[1])! ..< rowArray.count { var colArray = rowArray[i] //let colArray :NSMutableArray = rowArray.object(at: i) as! NSMutableArray for j in 0 ..< colArray.count { colArray[j] = "\(Int(keys[0])!)-\(i)-\(j)" // colArray.replaceObject(at: j, with: "\(keys.firstObject as! Int)-\(i)-\(j)") } rowArray[i] = colArray // rowArray.replaceObject(at: i, with: colArray) } localPartition[Int(keys[0])!] = rowArray //localPartition.replaceObject(at: keys.firstObject as! Int, with: rowArray) } }else{ localPartition.remove(at: Int(keys[0])!) //localPartition.removeObject(at: keys.firstObject as! Int) for i in Int(keys[0])! ..< localPartition.count { var rowArray = localPartition[i] //let rowArray :NSMutableArray = localPartition.object(at: i) as! NSMutableArray for j in 0 ..< rowArray.count { var colArray = rowArray[j] //let colArray :NSMutableArray = rowArray.object(at: j) as! NSMutableArray for k in 0 ..< colArray.count{ colArray[k] = "\(i)-\(j)-\(k)" //colArray.replaceObject(at: j, with: "\(i)-\(j)-\(k)") } rowArray[j] = colArray //rowArray.replaceObject(at: j, with: colArray) } localPartition[i] = rowArray } } } print("final update \(localPartition)") } func findWithIndex(array : [String],index i : Int = 0) -> String? { for j in 0...array.count { if j == i { return array[i] } } return nil } func getSingletonArray() -> Array<String>{ var returnArray = Array<String>() for (_,indexArray) in localPartition.enumerated(){ for (_,insideArray) in indexArray.enumerated(){ for (_,inside) in insideArray.enumerated(){ returnArray.append(inside) } } } return returnArray } func exchangeDataSource(sourceIndex:Int,destIndex:Int) { var temp = self.collectionArray[sourceIndex] self.collectionArray[sourceIndex] = self.collectionArray[destIndex] self.collectionArray[destIndex] = temp } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } //MARK: - showImagePicker func showImagePicker() { let pickerController = DKImagePickerController() pickerController.allowMultipleTypes = true pickerController.autoDownloadWhenAssetIsInCloud = true pickerController.showsCancelButton = true self.present(pickerController, animated: true) {} pickerController.didCancel = { () in self.navigationController?.dismiss(animated: true, completion: nil) //self.navigationController?.popViewController(animated: true) } pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in self.defaults.set(false, forKey: "FirstTimeUpload") print("didSelectAssets") if assets.count > 0{ self.startAnimation() } self.requestOptions.resizeMode = .exact self.requestOptions.deliveryMode = .highQualityFormat self.requestOptions.isSynchronous = false self.requestOptions.isNetworkAccessAllowed = true let manager: PHImageManager = PHImageManager.default() var assetsOriginal = [PHAsset]() for dKasset :DKAsset in assets{ assetsOriginal.append(dKasset.originalAsset!) } var newItemsArray = [[AnyHashable:Any]]() DispatchQueue.global(qos: .background).async { for asset: PHAsset in assetsOriginal { if asset.mediaType == .video { self.requestOptionsVideo.deliveryMode = .highQualityFormat self.requestOptionsVideo.isNetworkAccessAllowed = true manager.requestAVAsset(forVideo: asset, options: self.requestOptionsVideo, resultHandler: { (assert:AVAsset?, audio:AVAudioMix?, info:[AnyHashable : Any]?) in let UrlLocal: URL = ((assert as? AVURLAsset)?.url)! let videoData = NSData(contentsOf: UrlLocal) guard let track = AVAsset(url: UrlLocal).tracks(withMediaType: AVMediaTypeVideo).first else { return } // var tracks = ass.tracks(withMediaType: "AVMediaTypeVideo").first // let track = tracks let trackDimensions = track.naturalSize let length = (videoData?.length)! / 1000000 var dictToAdd = Dictionary<AnyHashable, Any>() dictToAdd.updateValue(UrlLocal, forKey: "item_url") dictToAdd.updateValue("", forKey: "cover") dictToAdd.updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176", forKey: "hexCode") dictToAdd.updateValue(trackDimensions, forKey: "item_size") dictToAdd.updateValue(videoData, forKey: "data") dictToAdd.updateValue(UrlLocal, forKey: "item_url") dictToAdd.updateValue("video", forKey: "type") newItemsArray.append(dictToAdd) if assetsOriginal.count == newItemsArray.count{ if(self.localPartition.count > 0){ self.defaults.set(newItemsArray.count, forKey: "addedMorePhotos") } var uploadViewController = self.storyboard?.instantiateViewController(withIdentifier: "ImagesUploadViewController") as! ImagesUploadViewController uploadViewController.uploadData = newItemsArray uploadViewController.storyId = String(self.randomNumber()) uploadViewController.dismissView = {(sender : UIViewController?,initialize:Bool?,newObjects:[[AnyHashable:Any]]?) -> Void in if self.collectionArray.count > 0{ self.defaults.set(true, forKey: "deletedAllItems") }else{ self.defaults.set(false, forKey: "deletedAllItems") } if self.localPartition.count > 0{ if !(initialize!){ self.scrollToPostionAfterUpload = self.collectionArray.count - 1 self.collectionArray.append(contentsOf: newObjects!) self.upload = true runOnMainThread { if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } self.reloadHeaderView = true self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() } } }else{ self.collectionArray = newObjects! self.scrollToPostionAfterUpload = 0 self.isFirstTime = true self.isLoadingStory = false runOnMainThread { self.reloadHeaderView = true let temp = self.collectionArray[0] var sizeOrg = temp["cloudFilePath"] as? String sizeOrg = URLConstants.imgDomain + sizeOrg! self.story_cover_photo_path = sizeOrg! self.getDataFromUrl(url: URL(string: sizeOrg!)!) { (data, response, error) in guard let data = data, error == nil else { return } self.coverdata = data DispatchQueue.main.async() { () -> Void in self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.view.addSubview(self.collectionView) self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.upload = true self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() //defaults.set(localPartition, forKey: "partition") if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } } } } } } self.present(uploadViewController, animated: true, completion: { self.stopAnimationLoader() }) } }) }else{ manager.requestImageData(for: asset, options: self.requestOptions, resultHandler: { (data: Data?, identificador: String?, orientaciomImage: UIImageOrientation, info: [AnyHashable: Any]?) in // print(info) var dictToAdd = Dictionary<AnyHashable, Any>() let compressedImage = UIImage(data: data!) // self.images.append(compressedImage!) let urlString = "\(((((info as! Dictionary<String,Any>)["PHImageFileURLKey"])! as! URL)))" dictToAdd.updateValue(urlString, forKey: "cloudFilePath") dictToAdd.updateValue(0, forKey: "cover") dictToAdd.updateValue(urlString, forKey: "filePath") dictToAdd.updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176", forKey: "hexCode") // dictToAdd.updateValue("#322e20,#d3d5db,#97989d,#aeb2b9,#858176" as AnyObject, forKey: "hexCode") let sizeImage = compressedImage?.size dictToAdd.updateValue(sizeImage, forKey: "item_size") dictToAdd.updateValue(urlString, forKey: "item_url") dictToAdd.updateValue(data, forKey: "data") dictToAdd.updateValue(sizeImage, forKey: "original_size") dictToAdd.updateValue("img", forKey: "type") newItemsArray.append(dictToAdd) if assetsOriginal.count == newItemsArray.count{ if(self.localPartition.count > 0){ self.defaults.set(newItemsArray.count, forKey: "addedMorePhotos") } var uploadViewController = self.storyboard?.instantiateViewController(withIdentifier: "ImagesUploadViewController") as! ImagesUploadViewController uploadViewController.uploadData = newItemsArray uploadViewController.storyId = String(self.randomNumber()) //let addHomes = self.storyboard?.instantiateViewController(withIdentifier: "AddHomesVC") as! AddHomesVC // var uploadViewController = ImagesUploadViewController(with: self.collectionArray, storyId: "5678") uploadViewController.dismissView = {(sender : UIViewController?,initialize:Bool?,newObjects:[[AnyHashable:Any]]?) -> Void in if self.collectionArray.count > 0{ self.defaults.set(true, forKey: "deletedAllItems") }else{ self.defaults.set(false, forKey: "deletedAllItems") } if self.localPartition.count > 0{ if !(initialize!){ self.scrollToPostionAfterUpload = self.collectionArray.count - 1 self.collectionArray.append(contentsOf: newObjects!) self.upload = true runOnMainThread { if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } self.reloadHeaderView = true self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() } } }else{ self.collectionArray = newObjects! self.scrollToPostionAfterUpload = 0 self.isFirstTime = true self.isLoadingStory = false runOnMainThread { self.reloadHeaderView = true let temp = self.collectionArray[0] var sizeOrg = temp["cloudFilePath"] as? String sizeOrg = URLConstants.imgDomain + sizeOrg! self.story_cover_photo_path = sizeOrg! self.getDataFromUrl(url: URL(string: sizeOrg!)!) { (data, response, error) in guard let data = data, error == nil else { return } self.coverdata = data DispatchQueue.main.async() { () -> Void in self.longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress)) self.collectionView.addGestureRecognizer(self.longPressGesture!) self.swapView = UIView(frame: CGRect.zero) self.swapImageView = UIImageView(image: UIImage(named: "Swap-white")) self.view.addSubview(self.collectionView) self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.upload = true self.getPhotobyupload() self.stopAnimationLoader() self.turnOnEditMode() if let local = self.defaults.object(forKey: "partition") as? Array<Array<Array<String>>>{ self.localPartition = local } } } } } } self.navigationController?.present(uploadViewController, animated: true, completion: { self.stopAnimationLoader() }) } }) } } } } } func getDataFromUrl(url: URL, completion: @escaping (_ data: UIImage?, _ response: URLResponse?, _ error: Error?) -> Void) { URLSession.shared.dataTask(with: url) { (data, response, error) in if let cachedVersion = cache.object(forKey: "\(url)" as NSString) { completion(cachedVersion, response, error) }else{ let image = UIImage(data: data!) cache.setObject(image!, forKey: "\(url)" as NSString) completion(image, response, error) } }.resume() } func IbaOpenGallery() { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: runOnMainThread { self.showImagePicker() } defaults.set(true, forKey: "forStoryMaking") break case .denied, .restricted : break //handle denied status case .notDetermined: // ask for permissions PHPhotoLibrary.requestAuthorization() { (status) -> Void in switch status { case .authorized: runOnMainThread { self.showImagePicker() } self.defaults.set(true, forKey: "forStoryMaking") // as above case .denied, .restricted: break // as above case .notDetermined: break // won't happen but still } } } } func selectPhotoFromPhotoLibrary() { } func getPhoto() { var totalPath = URLConstants.imgDomain for photoIndex in 0 ..< self.collectionArray.count { let temp = collectionArray[photoIndex] if let type = temp["type"] as? String{ if type == "Text"{ let textFrame = CGRect(x: 0, y: 0, width: SCREENWIDTH, height: SCREENHEIGHT - 100) let textImageView = UIView(frame: textFrame) let backgroundColor = temp["backgroundColor"] as? String ?? "" textImageView.backgroundColor = UIColor(hexString:backgroundColor) let title = temp["title"] as? String ?? "" let subTitle = temp["description"] as? String ?? "" let titleFont = UIFont(name: "Raleway-Regular", size: 18.0) let titleLabel = UILabel.init() titleLabel.text = title let textColor = temp["textColor"] as? String ?? "#000000" titleLabel.textColor = UIColor(hexString:textColor) titleLabel.numberOfLines = 0 titleLabel.font = titleFont // let textAlignment = temp["textAlignment"] as? Int ?? 1 let titleHeight = title.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titleFrame = CGRect(x: 10, y: 40, width: SCREENWIDTH - 20, height: 100) titleLabel.frame = titleFrame let descriptionLabel = UILabel.init() descriptionLabel.text = title descriptionLabel.textColor = UIColor(hexString:textColor) descriptionLabel.numberOfLines = 0 descriptionLabel.font = titleFont // descriptionLabel.textAlignment = .center // CGFloat titleHeight = [self getHeightForText:title withFont:titleFont andWidth:SCREENWIDTH - 20]; // CGRect titleFrame = CGRectMake(10.0, 40.0, SCREENWIDTH - 20, 100); // titleLabel.frame = titleFrame; // [textImageView addSubview:titleLabel]; let titledescriptionHeight = subTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titledescriptionFrame = CGRect(x: 10, y: titleHeight + 80, width: SCREENWIDTH - 20, height: titledescriptionHeight) descriptionLabel.frame = titledescriptionFrame if let allign = temp["textAlignment"] as? Int{ switch allign { case 0: titleLabel.textAlignment = .left descriptionLabel.textAlignment = .left case 1: titleLabel.textAlignment = .center descriptionLabel.textAlignment = .center case 2: titleLabel.textAlignment = .right descriptionLabel.textAlignment = .right case 3: titleLabel.textAlignment = .justified descriptionLabel.textAlignment = .justified default: break } } // titleLabel.textAlignment = .center // CGFloat titleHeight = [self getHeightForText:title withFont:titleFont andWidth:SCREENWIDTH - 20]; // CGRect titleFrame = CGRectMake(10.0, 40.0, SCREENWIDTH - 20, 100); // titleLabel.frame = titleFrame; // [textImageView addSubview:titleLabel]; textImageView.addSubview(titleLabel) textImageView.addSubview(descriptionLabel) let imageView = UIImage(view: textImageView) let Ptitle = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: Ptitle, video: false) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.video = false mutablePhotos.append(photo) }else{ var url = temp["item_url"] as! String //if url.contains("http"){ // totalPath = url if type == "img"{ var urlImage = url.components(separatedBy: "album") if urlImage.count == 2 { var second = urlImage[1] second.remove(at: second.startIndex) url = totalPath + second }else{ let first = urlImage[0] url = totalPath + first } var version = url.components(separatedBy: "compressed") var afterAppending = url.components(separatedBy: "compressed") var widthImage = (version[0]) + "1440" + (afterAppending[1]) // totalPath = URLConstants.imgDomain + widthImage let data = NSData.init(contentsOf: URL(string: widthImage)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title, video: false) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } mutablePhotos.append(photo) }else if type == "video"{ if let image = thumbnailImageForFileUrl(URL(string: url)!){ if let data = UIImagePNGRepresentation(image){ // let data = NSData.init(contentsOf: URL(string: totalPath)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title,videoUrl: url,video:true) // photo.videoUrl = URL(string: url)! //photo.video = true mutablePhotos.append(photo) } } } } }else{ var url = temp["item_url"] as? String if url != ""{ var urlImage = url?.components(separatedBy: "album") var totalPath = URLConstants.imgDomain url = totalPath + (urlImage?[1])! var version = url?.components(separatedBy: "compressed") var afterAppending = url?.components(separatedBy: "compressed") var widthImage = (version?[0])! + "1080" + (afterAppending?[1])! // let sizeOrg = (temp as AnyObject).object(forKey: "data") as? Data let data = NSData.init(contentsOf: URL(string: widthImage)!) let imageView = UIImage(data: data as! Data) //let image = images[photoIndex] let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title, video: false) mutablePhotos.append(photo) } } } } func getPhotobyupload() { for photoIndex in 0 ..< self.collectionArray.count { let temp = collectionArray[photoIndex] var totalPath = URLConstants.imgDomain let type = temp["type"] as! String if type == "Text"{ let textFrame = CGRect(x: 0, y: 0, width: SCREENWIDTH, height: SCREENHEIGHT - 100) let textImageView = UIView(frame: textFrame) textImageView.backgroundColor = UIColor.blue let title = temp["title"] as! String let subTitle = temp["description"] as! String let titleFont = UIFont(name: "Raleway-Regular", size: 18.0) let titleLabel = UILabel.init() titleLabel.text = title titleLabel.textColor = UIColor(hexString:temp["textColor"] as! String) titleLabel.numberOfLines = 0 titleLabel.font = titleFont titleLabel.textAlignment = .center let titleHeight = title.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titleFrame = CGRect(x: 10, y: 40, width: SCREENWIDTH - 20, height: 100) titleLabel.frame = titleFrame textImageView.addSubview(titleLabel) let descriptionLabel = UILabel.init() descriptionLabel.text = title descriptionLabel.textColor = UIColor(hexString:temp["textColor"] as! String) descriptionLabel.numberOfLines = 0 descriptionLabel.font = titleFont descriptionLabel.textAlignment = .center // CGFloat titleHeight = [self getHeightForText:title withFont:titleFont andWidth:SCREENWIDTH - 20]; // CGRect titleFrame = CGRectMake(10.0, 40.0, SCREENWIDTH - 20, 100); // titleLabel.frame = titleFrame; // [textImageView addSubview:titleLabel]; let titledescriptionHeight = subTitle.height(withConstrainedWidth: SCREENWIDTH - 20, font: titleFont!) let titledescriptionFrame = CGRect(x: 10, y: titleHeight + 80, width: SCREENWIDTH - 20, height: titledescriptionHeight) descriptionLabel.frame = titledescriptionFrame textImageView.addSubview(descriptionLabel) let imageView = UIImage(view: textImageView) let Ptitle = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: Ptitle, video: false) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.video = false mutablePhotos.append(photo) }else{ var url = temp["item_url"] as! String if type == "img"{ var urlImage = url.components(separatedBy: "album") if urlImage.count == 2 { var second = urlImage[1] second.remove(at: second.startIndex) url = totalPath + second }else{ let first = urlImage[0] url = totalPath + first } var version = url.components(separatedBy: "compressed") var afterAppending = url.components(separatedBy: "compressed") var widthImage = (version[0]) + "1920" + (afterAppending[1]) // totalPath = URLConstants.imgDomain + widthImage let data = NSData.init(contentsOf: URL(string: widthImage)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title, video: false) // // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.video = false mutablePhotos.append(photo) }else if type == "video"{ if let image = thumbnailImageForFileUrl(URL(string: url)!){ if let data = UIImagePNGRepresentation(image){ // let data = NSData.init(contentsOf: URL(string: totalPath)!) let imageView = UIImage(data: data as! Data) let title = NSAttributedString(string: "\(photoIndex + 1)", attributes: [NSForegroundColorAttributeName: UIColor.white]) let photo = ExamplePhoto(image: imageView, attributedCaptionTitle: title,videoUrl: url,video:true) // if photoIndex == CustomEverythingPhotoIndex { // photo.placeholderImage = UIImage(named: PlaceholderImageName) // } // photo.videoUrl = URL(string: url)! // photo.video = true mutablePhotos.append(photo) } } } } } } func thumbnailImageForFileUrl(_ fileUrl: URL) -> UIImage? { if let cachedVersion = cache.object(forKey: "\(fileUrl)" as NSString) { return cachedVersion }else{ let asset = AVAsset(url: fileUrl) let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.appliesPreferredTrackTransform = true let durationSeconds = CMTimeGetSeconds(asset.duration) do { let thumbnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(Int64(durationSeconds/1.0), 600), actualTime: nil) let images = UIImage(cgImage: thumbnailCGImage) cache.setObject(images, forKey: "\(fileUrl)" as NSString) return images } catch let err { print(err) } } return nil } } extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource,NYTPhotosViewControllerDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.collectionArray.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // UNDO This Comments if editTurnOn{ let previouslySelectedItem = selectedItemIndex if editingTextFieldIndex == -1{ if(selectedItemIndex == indexPath.item){ self.setInitialToolbarConfiguration() //[self setInitialToolbarConfiguration]; selectedItemIndex = -1 self.title = "" }else{ selectedItemIndex = indexPath.item let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if type == "Text"{ self.editToolbarConfigurationForTextCells() self.title = "Text" } else{ self.changeToEnrichMode() } } var indexPathsToReload = [IndexPath]() if previouslySelectedItem != -1{ indexPathsToReload.append(IndexPath(item: previouslySelectedItem, section: 0)) } if self.selectedItemIndex != -1{ indexPathsToReload.append(IndexPath(item: self.selectedItemIndex, section: 0)) } DispatchQueue.main.async { self.collectionView.performBatchUpdates({ print(indexPathsToReload) self.collectionView.reloadItems(at: indexPathsToReload) }, completion: { (test) in }) } } }else{ selectedIndexPath = indexPath.item let photosViewController = NYTPhotosViewController(photos: mutablePhotos) let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if type == "Text"{ guard let textCell = self.collectionView.cellForItem(at: indexPath) as? TextCellStoryCollectionViewCell else{ return } let screenshotOfTextCell = UIImage(view: textCell) }else if type == "video"{ guard let VideoCell = self.collectionView.cellForItem(at: indexPath) as? ImageViewCollectionViewCell else{ return } guard let player = VideoCell.player else { return } if (player.error == nil) && (player.rate == 0){ VideoCell.player.pause() }else{ VideoCell.player.play() } }else{ let set :IndexSet = [0] self.collectionView.reloadSections(set) selectedItemIndex = indexPath.row photosViewController.display(mutablePhotos[indexPath.row], animated: false) photosViewController.delegate = self self.present(photosViewController, animated: true, completion: nil) } } } func photosViewControllerDidDismiss(_ photosViewController: NYTPhotosViewController) { // self.collectionView.reloadData() } func photosViewController(_ photosViewController: NYTPhotosViewController, didNavigateTo photo: NYTPhoto, at photoIndex: UInt) { self.selectedIndexPath = Int(photoIndex) let visiblePaths = self.collectionView.indexPathsForVisibleItems if (visiblePaths.contains(IndexPath(item: self.selectedIndexPath, section: 0))){ self.collectionView.selectItem(at: IndexPath(item: self.selectedIndexPath, section: 0), animated: false, scrollPosition: .centeredVertically) } } func photosViewController(_ photosViewController: NYTPhotosViewController, referenceViewFor photo: NYTPhoto) -> UIView? { let itemAtIndex = self.collectionArray[selectedIndexPath] let type = itemAtIndex["type"] as? String ?? "Img" if type == "Text"{ guard let textCell = self.collectionView.cellForItem(at: IndexPath(item: selectedIndexPath, section: 0)) as? TextCellStoryCollectionViewCell else{ return nil } return textCell.contentView }else{ guard let imgCell = self.collectionView.cellForItem(at: IndexPath(item: selectedIndexPath, section: 0)) as? ImageViewCollectionViewCell else{ return nil } // let btn = UIButton(frame: CGRect(x: self.view.frame.size.width/2, y: self.view.frame.size.height/2, width: 40, height: 40)) // btn.addTarget(self, action: #selector(setBackgroundColorForTextCell(_:)), for: UIControlEvents.touchUpInside) // // // imgCell.contentView.addSubview(btn) return imgCell.contentView } return nil } // - (void)fullScreenButtonTapped:(UIButton *)sender { // // ImageCollectionViewCell *cell = (ImageCollectionViewCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:sender.tag inSection:0]]; // cell.player.muted = YES; // [cell.volumeButton setImage:[UIImage imageNamed:@"volume_mute"] forState:UIControlStateNormal]; // // NSURL *videoUrl = [NSURL URLWithString:[[_collectionViewItemsArray objectAtIndex:sender.tag] objectForKey:@"cloudFilePath"]]; // NSLog(@"singleTapf=gesture == %@",videoUrl); // // // AVPlayer *player = [AVPlayer playerWithURL:videoUrl]; // // // create a player view controller // AVPlayerViewController *controller = [[AVPlayerViewController alloc] init]; // [self presentViewController:controller animated:YES completion:nil]; // controller.player = player; // [player play]; // } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var size = CGSize.zero let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if isViewStory { if type == "Text"{ size = temp["item_size"] as? CGSize ?? CGSize(width: SCREENWIDTH, height: 200) // var cgsize = CGSizeFromString(sizeOrg) // size = cgsize }else{ let sizeOrg = temp["item_size"] as? CGSize size = sizeOrg! } }else{ if type == "video"{ size = temp["item_size"] as! CGSize // var cgsize = CGSizeFromString(sizeOrg!) //= cgsize }else if type == "Text"{ size = temp["item_size"] as? CGSize ?? CGSize(width: SCREENWIDTH, height: 200) // = CGSizeFromString(sizeOrg!) }else{ size = imageForIndexPath(indexPath) } } return size //CGSize(width: size.width*percentWidth/4, height: size.height/4) } func imageForIndexPath(_ indexPath:IndexPath) -> CGSize { let temp = collectionArray[indexPath.row] let sizeOrg = temp["item_size"] as? CGSize ?? CGSize.zero return sizeOrg } func getDataFromUrl(urL:URL, completion: @escaping ((_ data: NSData?) -> Void)) { URLSession.shared.dataTask(with: urL) { (data, response, error) in completion(data as NSData?) }.resume() } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if isViewStory { if type == "Text"{ if let cell = cell as? TextCellStoryCollectionViewCell{ if selectedItemIndex == indexPath.item{ cell.layer.borderWidth = 2 cell.layer.borderColor = UIColor(hexString:"#32C5B6").cgColor } cell.alpha = 1 cell.isHidden = false cell.titleLabel.isUserInteractionEnabled = false cell.subTitleLabel.isUserInteractionEnabled = false cell.layer.borderWidth = CGFloat.leastNormalMagnitude cell.layer.borderColor = UIColor.clear.cgColor if let title = temp["title"] as? String{ cell.titleLabel.text = title }else{ } if let subTitleLabel = temp["description"] as? String{ cell.subTitleLabel.text = subTitleLabel }else{ } //let backgroundColor = temp["backgroundColor"] as? String ?? "#ffffff" if let allign = temp["textAlignment"] as? Int{ switch allign { case 0: cell.titleLabel.textAlignment = .left cell.subTitleLabel.textAlignment = .left case 1: cell.titleLabel.textAlignment = .center cell.subTitleLabel.textAlignment = .center case 2: cell.titleLabel.textAlignment = .right cell.subTitleLabel.textAlignment = .right case 3: cell.titleLabel.textAlignment = .justified cell.subTitleLabel.textAlignment = .justified default: break } } //cell.titleLabel.inputAccessoryView = self.keyboardView //cell.subTitleLabel.inputAccessoryView = self.keyboardView if let textColor = temp["textColor"] as? String { cell.titleLabel.textColor = UIColor(hexString:textColor) }else{ cell.titleLabel.textColor = UIColor(hexString:"#ffffff") } if let backgroundColor = temp["backgroundColor"] as? String { cell.myView.backgroundColor = UIColor(hexString:backgroundColor) }else{ cell.myView.backgroundColor = UIColor(hexString:"#ffffff") } } }else{ if let imageViewCell = cell as? ImageViewCollectionViewCell{ if type == "video"{ imageViewCell.layer.borderWidth = CGFloat.leastNormalMagnitude imageViewCell.layer.borderColor = UIColor.clear.cgColor imageViewCell.videoAsSubView.isHidden = false imageViewCell.volumeBtn.isHidden = false //imageViewCell.fullScreenBtn.isHidden = false if let player_layer = temp["player_layer"] as? AVPlayerLayer{ let layer = temp["player"] as! AVPlayer if let isLayerPresent = (imageViewCell.videoAsSubView.layer.sublayers?.contains(player_layer)){ if !isLayerPresent{ imageViewCell.videoAsSubView.layer.addSublayer(player_layer) imageViewCell.player = layer //imageViewCell.playerItm = temp.playerItm imageViewCell.player.isMuted = false // imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill // imageViewCell.playerLayer.needsDisplayOnBoundsChange = true // imageViewCell.volumeBtn.setImage(UIImage(named: "icon_muted"), for: .normal) imageViewCell.player.play() NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) }else{ imageViewCell.videoAsSubView.layer.addSublayer(player_layer) imageViewCell.player = layer // imageViewCell.playerItm = temp.playerItm imageViewCell.player.isMuted = false //imageViewCell.iboSound.setImage(UIImage(named: "icon_muted"), for: .normal) imageViewCell.player.play() // imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill print("layer is there") // imageViewCell.playerLayer.needsDisplayOnBoundsChange = true NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) } }else{ // imageViewCell.iboVideoView.addGestureRecognizer(doubleTapVideo) // imageViewCell.iboVideoView.addGestureRecognizer(singleTapvideo) // singleTapvideo.require(toFail: doubleTapVideo) imageViewCell.videoAsSubView.layer.addSublayer(player_layer) imageViewCell.player = layer // imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill //imageViewCell.playerItm = temp.playerItm imageViewCell.player.isMuted = false // imageViewCell.iboSound.setImage(UIImage(named: "icon_muted"), for: .normal) imageViewCell.player.play() NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) } }else{ var video_url = temp["item_url"] as? String ?? "" if (video_url.contains("http")){ }else{ video_url = URLConstants.imgDomain + video_url } imageViewCell.videoAsSubView.isHidden = true // imageViewCell.volumeBtn.isHidden = true imageViewCell.imageViewToShow.image = UIImage(named: "process") imageViewCell.imageViewToShow.contentMode = .scaleAspectFill DispatchQueue.global(qos: .userInitiated).async { imageViewCell.playerItm = AVPlayerItem.init(url: URL(string: video_url)!) DispatchQueue.main.sync(execute: { imageViewCell.player = AVPlayer(playerItem: imageViewCell.playerItm) imageViewCell.playerLayer = AVPlayerLayer(player: imageViewCell.player) imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill imageViewCell.player.actionAtItemEnd = .none imageViewCell.playerLayer.frame = imageViewCell.videoAsSubView.bounds imageViewCell.playerLayer.needsDisplayOnBoundsChange = true //cell.playerLayer.frame = cell.videoAsSubview.bounds; imageViewCell.player.isMuted = true // imageViewCell.volumeBtn.setImage(UIImage(named: "icon_muted"), for: .normal) //cell.iboVideoView.layer.sublayers = nil imageViewCell.imageViewToShow.image = nil imageViewCell.videoAsSubView.isHidden = false // imageViewCell.volumeBtn.isHidden = false imageViewCell.videoAsSubView.layer.addSublayer(imageViewCell.playerLayer) imageViewCell.player.play() self.collectionArray[indexPath.row].updateValue(imageViewCell.playerLayer, forKey: "player_layer") self.collectionArray[indexPath.row].updateValue(imageViewCell.player, forKey: "player") //temp // dictToAdd.updateValue("Video" as AnyObject, forKey: "type") // temp.player = imageViewCell.player //temp.playerLayer = imageViewCell.playerLayer NotificationCenter.default.addObserver(self,selector: #selector(self.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: imageViewCell.player.currentItem) }) } } } else{ var url = temp["item_url"] as? String var urlImage = url?.components(separatedBy: "album") let totalPath = URLConstants.imgDomain if urlImage?.count == 2 { let second = urlImage?[1] url = totalPath + second! }else{ if let first = urlImage?[0]{ url = totalPath + first } } //url = totalPath + (urlImage?[1])! var version = url?.components(separatedBy: "compressed") var afterAppending = url?.components(separatedBy: "compressed") var widthImage = (version?[0])! + "1080" + (afterAppending?[1])! imageViewCell.imageViewToShow.sd_setImage(with: URL(string: widthImage), placeholderImage: UIImage(named: "")) imageViewCell.imageViewToShow.contentMode = .scaleAspectFill imageViewCell.videoAsSubView.isHidden = true imageViewCell.volumeBtn.isHidden = true //imageViewCell.fullScreenBtn.isHidden = true imageViewCell.videoPlayBtn.isHidden = true //imageViewCell.backgroundColor = UIColor.brown imageViewCell.clipsToBounds = true } } } }else{ // edit mode On if let imageViewCell = cell as? ImageViewCollectionViewCell{ if selectedItemIndex == indexPath.item{ imageViewCell.layer.borderWidth = 2 imageViewCell.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } //imageViewCell.alpha = 1 // imageViewCell.isHidden = false if type == "img"{ let temp = collectionArray[indexPath.row] var url = temp["item_url"] as? String var urlImage = url?.components(separatedBy: "album") let totalPath = URLConstants.imgDomain if urlImage?.count == 2 { let second = urlImage?[1] url = totalPath + second! }else{ if let first = urlImage?[0]{ url = totalPath + first } } //url = totalPath + (urlImage?[1])! var version = url?.components(separatedBy: "compressed") var afterAppending = url?.components(separatedBy: "compressed") var widthImage = (version?[0])! + "1080" + (afterAppending?[1])! imageViewCell.videoAsSubView.isHidden = true imageViewCell.videoPlayBtn.isHidden = true imageViewCell.volumeBtn.isHidden = true //imageViewCell.fullScreenBtn.isHidden = true imageViewCell.imageViewToShow.sd_setImage(with: URL(string: widthImage), placeholderImage: UIImage(named: "")) imageViewCell.imageViewToShow.contentMode = .scaleAspectFill imageViewCell.clipsToBounds = true }else if type == "video"{ let temp = collectionArray[indexPath.row] imageViewCell.videoAsSubView.layer.sublayers = nil imageViewCell.videoAsSubView.isHidden = false imageViewCell.volumeBtn.isHidden = false // imageViewCell.player.isMuted = true //imageViewCell.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill //imageViewCell.playerLayer.needsDisplayOnBoundsChange = true imageViewCell.layer.borderWidth = CGFloat.leastNormalMagnitude imageViewCell.layer.borderColor = UIColor.clear.cgColor // imageViewCell.player.pause() DispatchQueue.global(qos: .userInitiated).async { var url = temp["item_url"] as? String ?? "" if (url.contains("http")){ }else{ url = URLConstants.imgDomain + url } if let image = self.thumbnailImageForFileUrl(URL(string: url)!){ DispatchQueue.main.async { imageViewCell.imageViewToShow.image = image } } } } }else{ if type == "Text"{ if let cell = cell as? TextCellStoryCollectionViewCell{ if selectedItemIndex == indexPath.item{ cell.layer.borderWidth = 2 cell.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } cell.alpha = 1 cell.isHidden = false cell.titleLabel.isUserInteractionEnabled = false cell.subTitleLabel.isUserInteractionEnabled = false cell.layer.borderWidth = CGFloat.leastNormalMagnitude cell.layer.borderColor = UIColor.clear.cgColor cell.titleLabel.text = temp["title"] as! String cell.subTitleLabel.text = temp["description"] as! String //cell.subTitleLabel.textColor = if let allign = temp["textAlignment"] as? Int{ switch allign { case 0: cell.titleLabel.textAlignment = .left cell.subTitleLabel.textAlignment = .left case 1: cell.titleLabel.textAlignment = .center cell.subTitleLabel.textAlignment = .center case 2: cell.titleLabel.textAlignment = .right cell.subTitleLabel.textAlignment = .right case 3: cell.titleLabel.textAlignment = .justified cell.subTitleLabel.textAlignment = .justified default: break } } //cell.titleLabel.inputAccessoryView = self.keyboardView //cell.subTitleLabel.inputAccessoryView = self.keyboardView cell.titleLabel.textColor = UIColor(hexString:(temp["textColor"] as? String ?? "#ffffff")) cell.myView.backgroundColor = UIColor(hexString:(temp["backgroundColor"] as? String ?? "#ffffff")) } } } } } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if !editTurnOn{ let indexData = self.collectionArray[indexPath.item] let type = indexData["type"] as! String if type == "video" { if let cell1 = cell as? ImageViewCollectionViewCell{ //cell1.player.replaceCurrentItem(with: nil) if let player = cell1.player{ player.isMuted = true } } } } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let temp = collectionArray[indexPath.row] let type = temp["type"] as! String if type == "Text" { var textViewCell:TextCellStoryCollectionViewCell! if (textViewCell == nil) { textViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellTextIdentifier, for: indexPath) as! TextCellStoryCollectionViewCell } textViewCell.myView.layer.borderWidth = CGFloat.greatestFiniteMagnitude textViewCell.myView.layer.borderColor = UIColor.clear.cgColor if editTurnOn { if selectedItemIndex == indexPath.item{ textViewCell.myView.layer.borderWidth = 2 // textViewCell.backgroundColor = UIColor.red textViewCell.myView.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } } return textViewCell }else{ var imageViewCell:ImageViewCollectionViewCell! if (imageViewCell == nil) { imageViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellIdentifier, for: indexPath) as! ImageViewCollectionViewCell } imageViewCell.layer.borderWidth = CGFloat.greatestFiniteMagnitude imageViewCell.layer.borderColor = UIColor.clear.cgColor if editTurnOn { if selectedItemIndex == indexPath.item{ imageViewCell.layer.borderWidth = 2 imageViewCell.layer.borderColor = UIColor(red: 50/255, green: 197/255, blue: 182/255, alpha: 1).cgColor } } if type != "video"{ let code = temp["hexCode"] as? String ?? "#e0cfb9" let components = code.components(separatedBy: ",") imageViewCell.backgroundColor = UIColor(hexString:components.first!) } //imageViewCell.alpha = 1 // imageViewCell.isHidden = false imageViewCell.layer.shouldRasterize = true; imageViewCell.layer.rasterizationScale = UIScreen.main.scale return imageViewCell } } func restartVideoFromBeginning(notification:NSNotification) { let seconds : Int64 = 0 let preferredTimeScale : Int32 = 1 let seekTime : CMTime = CMTimeMake(seconds, preferredTimeScale) let player : AVPlayerItem = notification.object as! AVPlayerItem player.seek(to: seekTime) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } } extension String { var parseJSONString: AnyObject? { let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false) if let jsonData = data { // Will return an object or nil if JSON decoding fails return try! JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject? } else { // Lossless conversion of the string was not possible return nil } } } extension Dictionary { mutating func update(other:Dictionary) { for (key,value) in other { self.updateValue(value, forKey:key) } } }
mit
a36799375d4e4ba8c9c8b52d9d30c400
47.640753
282
0.465848
6.226671
false
false
false
false
Desgard/Calendouer-iOS
Calendouer/Calendouer/App/Tools/Agrume/ImageDownloader.swift
1
728
// // Copyright © 2016 Schnaub. All rights reserved. // import Foundation import UIKit final class ImageDownloader { class func downloadImage(_ url: URL, completion: @escaping (_ image: UIImage?) -> Void) -> URLSessionDataTask? { let dataTask = URLSession.shared.dataTask(with: url) { data, _, error in guard error == nil else { completion(nil) return } DispatchQueue.global(qos: .userInitiated).async { var image: UIImage? defer { DispatchQueue.main.async { completion(image) } } guard let data = data else { return } image = UIImage(data: data) } } dataTask.resume() return dataTask } }
mit
c187640c65f2aa2bef9b26ecf3322427
21.71875
114
0.590096
4.406061
false
false
false
false
insidegui/WWDC
Packages/ConfCore/ConfCore/TranscriptIndexer.swift
1
6884
// // TranscriptIndexer.swift // WWDC // // Created by Guilherme Rambo on 27/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import RealmSwift import Transcripts import os.log 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 { private let storage: Storage private static let log = OSLog(subsystem: "ConfCore", category: "TranscriptIndexer") private let log = TranscriptIndexer.log public var manifestURL: URL public var ignoreExistingEtags = false public init(_ storage: Storage, manifestURL: URL) { self.storage = storage self.manifestURL = manifestURL } fileprivate let queue = DispatchQueue(label: "Transcript Indexer", qos: .background) fileprivate lazy var backgroundOperationQueue: OperationQueue = { let q = OperationQueue() q.underlyingQueue = self.queue q.name = "Transcript Indexing" return q }() private lazy var onQueueRealm: Realm = { // swiftlint:disable:next force_try try! storage.makeRealm() }() /// How many days before transcripts will be refreshed based on the remote manifest, ignoring /// sessions which already have local transcripts. private static let minimumIntervalInDaysBetweenManifestBasedUpdates = 5 /// The last time a transcript fetch was performed based on the remote manifest. public static var lastManifestBasedUpdateDate: Date { get { UserDefaults.standard.object(forKey: #function) as? Date ?? .distantPast } set { UserDefaults.standard.set(newValue, forKey: #function) } } private static var shouldFetchRemoteManifest: Bool { guard let days = Calendar.current.dateComponents(Set([.day]), from: lastManifestBasedUpdateDate, to: Date()).day else { return false } return days > minimumIntervalInDaysBetweenManifestBasedUpdates } public static let minTranscriptableSessionLimit: Int = 30 public static let transcriptableSessionsPredicate: NSPredicate = NSPredicate(format: "ANY event.year > 2012 AND ANY event.year <= 2020 AND transcriptIdentifier == '' AND SUBQUERY(assets, $asset, $asset.rawAssetType == %@).@count > 0", SessionAssetType.streamingVideo.rawValue) public static func needsUpdate(in storage: Storage) -> Bool { // Manifest-based updates. guard !shouldFetchRemoteManifest else { os_log("Transcripts will be checked against remote manifest", log: self.log, type: .debug) return true } // Local cache-based updates. let transcriptedSessions = storage.realm.objects(Session.self).filter(TranscriptIndexer.transcriptableSessionsPredicate) return transcriptedSessions.count > minTranscriptableSessionLimit } private func makeDownloader() -> TranscriptDownloader { TranscriptDownloader(manifestURL: manifestURL, storage: self) } private lazy var downloader: TranscriptDownloader = { makeDownloader() }() var didStart: () -> Void = { } var progressChanged: (Float) -> Void = { _ in } var didStop: () -> Void = { } public func downloadTranscriptsIfNeeded() { downloader = makeDownloader() didStart() DistributedNotificationCenter.default().postNotificationName( .TranscriptIndexingDidStart, object: nil, userInfo: nil, options: .deliverImmediately ) do { let realm = try storage.makeRealm() let knownSessionIds = Array(realm.objects(Session.self).map(\.identifier)) os_log("Got %d session IDs", log: self.log, type: .debug, knownSessionIds.count) downloader.fetch(validSessionIdentifiers: knownSessionIds, progress: { [weak self] progress in guard let self = self else { return } os_log("Transcript indexing progresss: %.2f", log: self.log, type: .default, progress) self.progressChanged(progress) }) { [weak self] in self?.finished() } } catch { os_log("Failed to initialize Realm: %{public}@", log: self.log, type: .fault, String(describing: error)) } } fileprivate func store(_ transcripts: [Transcript]) { storage.backgroundUpdate { [weak self] backgroundRealm in guard let self = self else { return } os_log("Start transcript realm updates", log: self.log, type: .debug) transcripts.forEach { transcript in guard let session = backgroundRealm.object(ofType: Session.self, forPrimaryKey: transcript.identifier) else { os_log("Corresponding session not found for transcript with identifier %{public}@", log: self.log, type: .error, transcript.identifier) return } session.transcriptIdentifier = transcript.identifier session.transcriptText = transcript.fullText backgroundRealm.add(transcript, update: .modified) } os_log("Finished transcript realm updates", log: self.log, type: .debug) } } private func finished() { didStop() DistributedNotificationCenter.default().postNotificationName( .TranscriptIndexingDidStop, object: nil, userInfo: nil, options: .deliverImmediately ) } } extension TranscriptIndexer: TranscriptStorage { public func previousEtag(for identifier: String) -> String? { guard !ignoreExistingEtags else { return nil } return onQueueRealm.object(ofType: Transcript.self, forPrimaryKey: identifier)?.etag } public func store(_ transcripts: [TranscriptContent], manifest: TranscriptManifest) { let transcriptObjects: [Transcript] = transcripts.map { model in let obj = Transcript() obj.identifier = model.identifier obj.fullText = model.lines.map(\.text).joined() obj.etag = manifest.individual[model.identifier]?.etag let annotations: [TranscriptAnnotation] = model.lines.map { model in let obj = TranscriptAnnotation() obj.timecode = Double(model.time) obj.body = model.text.replacingOccurrences(of: "\n", with: "") return obj } obj.annotations.append(objectsIn: annotations) return obj } store(transcriptObjects) } }
bsd-2-clause
0f1bcc7bbfd333a733f49c326a5a4f45
34.117347
280
0.645358
4.958934
false
false
false
false
SuperJerry/Swift
sorting.playground/Contents.swift
1
1085
//: Playground - noun: a place where people can play //import UIKit //var str = "Hello, playground" var list = [1,2,3,5,8,13,21,34,55,89,144,233,377,610] public func linear(key: Int){ for number in list { if number == key{ var result = "value \(key) found" println(result) //break return } } println("value \(key) not found") } //linear(144) func round(n: Double)-> Double{ if Int(2*n) > 2*Int(n){ return Double(Int(n+1)) } return Double(Int(n)) } //println(round(2.9999)) public func log(key: Int, imin: Int, imax: Int){ if (imin == imax) && (list[imin] != key) { println("not found") return } var midindex: Double = round(Double((imin + imax) / 2)) var midnumber = list[Int(midindex)] if midnumber > key { log(key, imin, Int(midindex)-1) }else if midnumber < key{ log(key, Int(midindex) + 1, imax) }else{ var result = "value \(key) found" println(result) } } log(233, 0, 13) //isFound
mit
a73a3ff6fb425123e992d61303dfbe96
17.389831
59
0.538249
3.135838
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Alamofire/Source/ParameterEncoding.swift
42
19679
// // ParameterEncoding.swift // // Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// HTTP method definitions. /// /// See https://tools.ietf.org/html/rfc7231#section-4.3 public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } // MARK: - /// A dictionary of parameters to apply to a `URLRequest`. public typealias Parameters = [String: Any] /// A type used to define how a set of parameters are applied to a `URLRequest`. public protocol ParameterEncoding { /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. /// /// - returns: The encoded request. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } // MARK: - /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as /// the HTTP body depends on the destination of the encoding. /// /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. /// /// There is no published specification for how to encode collection types. By default the convention of appending /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the /// square brackets appended to array keys. /// /// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. public struct URLEncoding: ParameterEncoding { // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// requests and sets as the HTTP body for requests with any other HTTP method. /// - queryString: Sets or appends encoded query string result to existing query string. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. public enum Destination { case methodDependent, queryString, httpBody } /// Configures how `Array` parameters are encoded. /// /// - brackets: An empty set of square brackets is appended to the key for every value. /// This is the default behavior. /// - noBrackets: No brackets are appended. The key is encoded as is. public enum ArrayEncoding { case brackets, noBrackets func encode(key: String) -> String { switch self { case .brackets: return "\(key)[]" case .noBrackets: return key } } } /// Configures how `Bool` parameters are encoded. /// /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. /// - literal: Encode `true` and `false` as string literals. public enum BoolEncoding { case numeric, literal func encode(value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal: return value ? "true" : "false" } } } // MARK: Properties /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var methodDependent: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } /// Returns a `URLEncoding` instance with an `.httpBody` destination. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination /// The encoding to use for `Array` parameters. public let arrayEncoding: ArrayEncoding /// The encoding to use for `Bool` parameters. public let boolEncoding: BoolEncoding // MARK: Initialization /// Creates a `URLEncoding` instance using the specified destination. /// /// - parameter destination: The destination defining where the encoded query string is to be applied. /// - parameter arrayEncoding: The encoding to use for `Array` parameters. /// - parameter boolEncoding: The encoding to use for `Bool` parameters. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { self.destination = destination self.arrayEncoding = arrayEncoding self.boolEncoding = boolEncoding } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) } return urlRequest } /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. /// /// - parameter key: The key of the query component. /// - parameter value: The value of the query component. /// /// - returns: The percent-escaped, URL encoded query string components. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) } } else if let value = value as? NSNumber { if value.isBool { components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { components.append((escape(key), escape(boolEncoding.encode(value: bool)))) } else { components.append((escape(key), escape("\(value)"))) } return components } /// Returns a percent-escaped string following RFC 3986 for a query string key or value. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. /// /// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = string[range] escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring) index = endIndex } } return escaped } private func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } private func encodesParametersInURL(with method: HTTPMethod) -> Bool { switch destination { case .queryString: return true case .httpBody: return false default: break } switch method { case .get, .head, .delete: return true default: return false } } } // MARK: - /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. public struct JSONEncoding: ParameterEncoding { // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. public static var `default`: JSONEncoding { return JSONEncoding() } /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } /// The options for writing the parameters as JSON data. public let options: JSONSerialization.WritingOptions // MARK: Initialization /// Creates a `JSONEncoding` instance using the specified options. /// /// - parameter options: The options for writing the parameters as JSON data. /// /// - returns: The new `JSONEncoding` instance. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. /// /// - parameter urlRequest: The request to apply the JSON object to. /// - parameter jsonObject: The JSON object to apply to the request. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let jsonObject = jsonObject else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } } // MARK: - /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header /// field of an encoded request is set to `application/x-plist`. public struct PropertyListEncoding: ParameterEncoding { // MARK: Properties /// Returns a default `PropertyListEncoding` instance. public static var `default`: PropertyListEncoding { return PropertyListEncoding() } /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } /// The property list serialization format. public let format: PropertyListSerialization.PropertyListFormat /// The options for writing the parameters as plist data. public let options: PropertyListSerialization.WriteOptions // MARK: Initialization /// Creates a `PropertyListEncoding` instance using the specified format and options. /// /// - parameter format: The property list serialization format. /// - parameter options: The options for writing the parameters as plist data. /// /// - returns: The new `PropertyListEncoding` instance. public init( format: PropertyListSerialization.PropertyListFormat = .xml, options: PropertyListSerialization.WriteOptions = 0) { self.format = format self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) } return urlRequest } } // MARK: - extension NSNumber { fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } }
mit
72a17fef55f49849045b6bee0023c213
39.743271
143
0.642106
5.0706
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Components/Currency/Money/Money+Sign.swift
1
2210
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import Foundation extension Money { /// A structure representing signs (+/-) used to display money. public struct Sign: Hashable { /// The string used to represent a positive sign for positive values. public let positive: String /// The string used to represent a negative sign for negative values. public let negative: String public init(positive: String, negative: String) { self.positive = positive self.negative = negative } } } // MARK: - Built-in extension Money.Sign { /// ```swift /// // When the amount is positive then the output is "". /// let amount = Money(120.30) /// .sign(.default) // ← Specifying sign output /// /// print(amount) // "$120.30" /// /// // When the amount is negative then the output is "-". /// let amount = Money(-120.30) /// .sign(.default) // ← Specifying sign output /// /// print(amount) // "-$120.30" /// ``` public static var `default`: Self { .init(positive: "", negative: "-") } /// ```swift /// // When the amount is positive then the output is "+". /// let amount = Money(120.30) /// .sign(.both) // ← Specifying sign output /// /// print(amount) // "+$120.30" /// /// // When the amount is negative then the output is "-". /// let amount = Money(-120.30) /// .sign(.both) // ← Specifying sign output /// /// print(amount) // "-$120.30" /// ``` public static var both: Self { .init(positive: "+", negative: "-") } /// ```swift /// // When the amount is positive then the output is "". /// let amount = Money(120.30) /// .sign(.none) // ← Specifying sign output /// /// print(amount) // "$120.30" /// /// // When the amount is negative then the output is "". /// let amount = Money(-120.30) /// .sign(.none) // ← Specifying sign output /// /// print(amount) // "$120.30" /// ``` public static var none: Self { .init(positive: "", negative: "") } }
mit
da7c1f5e966eae7c8cff9f3cb146eea4
27.166667
77
0.535275
4.053506
false
false
false
false
aschwaighofer/swift
test/Driver/Dependencies/one-way-depends-before-fine.swift
2
3634
/// other ==>+ main /// other | main // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/one-way-depends-before-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/one-way-depends-before-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST-NOT: Handled // RUN: touch -t 201401240006 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND: Handled main.swift // CHECK-SECOND: Handled other.swift // RUN: touch -t 201401240007 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD-NOT: Handled main.swift // CHECK-THIRD: Handled other.swift // CHECK-THIRD-NOT: Handled main.swift // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/one-way-depends-before-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/one-way-depends-before-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: touch -t 201401240006 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s // CHECK-FOURTH-NOT: Handled other.swift // CHECK-FOURTH: Handled main.swift // CHECK-FOURTH-NOT: Handled other.swift // RUN: touch -t 201401240007 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s // RUN: touch -t 201401240008 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s
apache-2.0
549e9613a22a35eee49e7366ddf8ac63
63.892857
284
0.712163
3.105983
false
false
true
false
nicholascross/WeakDictionary
WeakDictionary/WeakKeyDictionary.swift
1
4004
// // WeakKeyDictionary.swift // WeakDictionary-iOS // // Created by Nicholas Cross on 2/1/19. // Copyright © 2019 Nicholas Cross. All rights reserved. // import Foundation public struct WeakKeyDictionary<Key: AnyObject & Hashable, Value: AnyObject> { private var storage: WeakDictionary<WeakDictionaryKey<Key, Value>, Value> private let valuesRetainedByKey: Bool public init(valuesRetainedByKey: Bool = false) { self.init( storage: WeakDictionary<WeakDictionaryKey<Key, Value>, Value>(), valuesRetainedByKey: valuesRetainedByKey ) } public init(dictionary: [Key: Value], valuesRetainedByKey: Bool = false) { var newStorage = WeakDictionary<WeakDictionaryKey<Key, Value>, Value>() dictionary.forEach { key, value in var keyRef: WeakDictionaryKey<Key, Value>! if valuesRetainedByKey { keyRef = WeakDictionaryKey<Key, Value>(key: key, value: value) } else { keyRef = WeakDictionaryKey<Key, Value>(key: key) } newStorage[keyRef] = value } self.init(storage: newStorage, valuesRetainedByKey: valuesRetainedByKey) } private init(storage: WeakDictionary<WeakDictionaryKey<Key, Value>, Value>, valuesRetainedByKey: Bool = false) { self.storage = storage self.valuesRetainedByKey = valuesRetainedByKey } public mutating func reap() { storage = weakKeyDictionary().storage } public func weakDictionary() -> WeakDictionary<Key, Value> { return dictionary().weakDictionary() } public func weakKeyDictionary() -> WeakKeyDictionary<Key, Value> { return self[startIndex ..< endIndex] } public func dictionary() -> [Key: Value] { var newStorage = [Key: Value]() storage.forEach { key, value in if let retainedKey = key.key, let retainedValue = value.value { newStorage[retainedKey] = retainedValue } } return newStorage } } extension WeakKeyDictionary: Collection { public typealias Index = DictionaryIndex<WeakDictionaryKey<Key, Value>, WeakDictionaryReference<Value>> public var startIndex: Index { return storage.startIndex } public var endIndex: Index { return storage.endIndex } public func index(after index: Index) -> Index { return storage.index(after: index) } public subscript(position: Index) -> (WeakDictionaryKey<Key, Value>, WeakDictionaryReference<Value>) { return storage[position] } public subscript(key: Key) -> Value? { get { return storage[WeakDictionaryKey<Key, Value>(key: key)] } set { let retainedValue = valuesRetainedByKey ? newValue : nil let weakKey = WeakDictionaryKey<Key, Value>(key: key, value: retainedValue) storage[weakKey] = newValue } } public subscript(bounds: Range<Index>) -> WeakKeyDictionary<Key, Value> { let subStorage = storage[bounds.lowerBound ..< bounds.upperBound] var newStorage = WeakDictionary<WeakDictionaryKey<Key, Value>, Value>() subStorage.filter { key, value in return key.key != nil && value.value != nil } .forEach { key, value in newStorage[key] = value.value } return WeakKeyDictionary<Key, Value>(storage: newStorage) } } extension WeakDictionary where Key: AnyObject { public func weakKeyDictionary(valuesRetainedByKey: Bool = false) -> WeakKeyDictionary<Key, Value> { return WeakKeyDictionary<Key, Value>(dictionary: dictionary(), valuesRetainedByKey: valuesRetainedByKey) } } extension Dictionary where Key: AnyObject, Value: AnyObject { public func weakKeyDictionary(valuesRetainedByKey: Bool = false) -> WeakKeyDictionary<Key, Value> { return WeakKeyDictionary<Key, Value>(dictionary: self, valuesRetainedByKey: valuesRetainedByKey) } }
mit
a1bb02e2d43c79beafc79ca9623ce7a9
31.282258
116
0.656008
4.442841
false
false
false
false
nifty-swift/Nifty
Sources/warning.swift
2
1289
/*************************************************************************************************** * warning.swift * * This file provides functonality for signaling and handling warnings. * * Author: Philip Erickson * Creation Date: 21 Feb 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2017 Philip Erickson **************************************************************************************************/ // FIXME: flesh out warning function--this is just a stub... public func warning( _ msg: String, handler: ((() -> Void)?) = nil, file: String = #file, function: String = #function, line: Int = #line) { print("Warning: \(msg).\t[\(file), \(function), line \(line)]") if let h = handler { h() } }
apache-2.0
7eacbe7855572153742cf3a0bf8b2f0d
36.911765
101
0.570209
4.522807
false
false
false
false
Witcast/witcast-ios
Pods/Material/Sources/Frameworks/Motion/Sources/Extensions/Motion+UIViewController.swift
1
11530
/* * The MIT License (MIT) * * Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Original Inspiration & Author * Copyright (c) 2016 Luke Zhao <me@lkzhao.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit fileprivate var AssociatedInstanceKey: UInt8 = 0 fileprivate struct AssociatedInstance { /// A reference to the modal animation. var modalTransitionType: MotionTransitionType /// A reference to the navigation animation. var navigationTransitionType: MotionTransitionType /// A reference to the tabBar animation. var tabBarTransitionType: MotionTransitionType /// A reference to the stored snapshot. var storedSnapshot: UIView? /** A reference to the previous navigation controller delegate before Motion was enabled. */ var previousNavigationDelegate: UINavigationControllerDelegate? /** A reference to the previous tab bar controller delegate before Motion was enabled. */ var previousTabBarDelegate: UITabBarControllerDelegate? } extension UIViewController { /// AssociatedInstance reference. fileprivate var associatedInstance: AssociatedInstance { get { return AssociatedObject.get(base: self, key: &AssociatedInstanceKey) { return AssociatedInstance(modalTransitionType: .auto, navigationTransitionType: .auto, tabBarTransitionType: .auto, storedSnapshot: nil, previousNavigationDelegate: nil, previousTabBarDelegate: nil) } } set(value) { AssociatedObject.set(base: self, key: &AssociatedInstanceKey, value: value) } } /// default motion animation type for presenting & dismissing modally public var motionModalTransitionType: MotionTransitionType { get { return associatedInstance.modalTransitionType } set(value) { associatedInstance.modalTransitionType = value } } /// used for .overFullScreen presentation internal var motionStoredSnapshot: UIView? { get { return associatedInstance.storedSnapshot } set(value) { associatedInstance.storedSnapshot = value } } /** A reference to the previous navigation controller delegate before Motion was enabled. */ internal var previousNavigationDelegate: UINavigationControllerDelegate? { get { return associatedInstance.previousNavigationDelegate } set(value) { associatedInstance.previousNavigationDelegate = value } } /** A reference to the previous tab bar controller delegate before Motion was enabled. */ internal var previousTabBarDelegate: UITabBarControllerDelegate? { get { return associatedInstance.previousTabBarDelegate } set(value) { associatedInstance.previousTabBarDelegate = value } } ///A boolean that indicates whether Motion is enabled or disabled. @IBInspectable public var isMotionEnabled: Bool { get { return transitioningDelegate is Motion } set(value) { guard value != isMotionEnabled else { return } if value { transitioningDelegate = Motion.shared if let v = self as? UINavigationController { previousNavigationDelegate = v.delegate v.delegate = Motion.shared } if let v = self as? UITabBarController { previousTabBarDelegate = v.delegate v.delegate = Motion.shared } } else { transitioningDelegate = nil if let v = self as? UINavigationController, v.delegate is Motion { v.delegate = previousNavigationDelegate } if let v = self as? UITabBarController, v.delegate is Motion { v.delegate = previousTabBarDelegate } } } } } extension UINavigationController { /// Default motion animation type for push and pop within the navigation controller. public var motionNavigationTransitionType: MotionTransitionType { get { return associatedInstance.navigationTransitionType } set(value) { associatedInstance.navigationTransitionType = value } } } extension UITabBarController { /// Default motion animation type for switching tabs within the tab bar controller. public var motionTabBarTransitionType: MotionTransitionType { get { return associatedInstance.tabBarTransitionType } set(value) { associatedInstance.tabBarTransitionType = value } } } extension UIViewController { /** Dismiss the current view controller with animation. Will perform a navigationController.popViewController if the current view controller is contained inside a navigationController */ @IBAction public func motionDismissViewController() { if let v = navigationController, self != v.viewControllers.first { v.popViewController(animated: true) } else { dismiss(animated: true) } } /// Unwind to the root view controller using Motion. @IBAction public func motionUnwindToRootViewController() { motionUnwindToViewController { $0.presentingViewController == nil } } /// Unwind to a specific view controller using Motion. public func motionUnwindToViewController(_ toViewController: UIViewController) { motionUnwindToViewController { $0 == toViewController } } /// Unwind to a view controller that responds to the given selector using Motion. public func motionUnwindToViewController(withSelector: Selector) { motionUnwindToViewController { $0.responds(to: withSelector) } } /// Unwind to a view controller with given class using Motion public func motionUnwindToViewController(withClass: AnyClass) { motionUnwindToViewController { $0.isKind(of: withClass) } } /// Unwind to a view controller that the matchBlock returns true on. public func motionUnwindToViewController(withMatchBlock: (UIViewController) -> Bool) { var target: UIViewController? var current: UIViewController? = self while nil == target && nil != current { if let childViewControllers = (current as? UINavigationController)?.childViewControllers ?? current!.navigationController?.childViewControllers { for v in childViewControllers.reversed() { if self != v, withMatchBlock(v) { target = v break } } } guard nil == target else { continue } current = current?.presentingViewController guard let v = current, withMatchBlock(v) else { continue } target = v } guard let v = target else { return } guard nil != v.presentedViewController else { v.navigationController?.popToViewController(v, animated: true) return } v.navigationController?.popToViewController(v, animated: false) let fromVC = navigationController ?? self let toVC = v.navigationController ?? v if v.presentedViewController != fromVC { /** UIKit's UIViewController.dismiss will jump to target.presentedViewController then perform the dismiss. We overcome this behavior by inserting a snapshot into target.presentedViewController And also force Motion to use the current view controller as the fromViewController. */ Motion.shared.fromViewController = fromVC guard let snapshot = fromVC.view.snapshotView(afterScreenUpdates: true) else { return } toVC.presentedViewController?.view.addSubview(snapshot) } toVC.dismiss(animated: true) } /** Replace the current view controller with another view controller within the navigation/modal stack. - Parameter with next: A UIViewController. */ public func motionReplaceViewController(with next: UIViewController) { guard !Motion.shared.isTransitioning else { print("motionReplaceViewController cancelled because Motion was doing a transition. Use Motion.shared.cancel(animated: false) or Motion.shared.end(animated: false) to stop the transition first before calling motionReplaceViewController.") return } if let nc = navigationController { var v = nc.childViewControllers if !v.isEmpty { v.removeLast() v.append(next) } if nc.isMotionEnabled { Motion.shared.forceNonInteractive = true } nc.setViewControllers(v, animated: true) } else if let container = view.superview { let presentingVC = presentingViewController Motion.shared.transition(from: self, to: next, in: container) { [weak self] (isFinished) in guard isFinished else { return } UIApplication.shared.keyWindow?.addSubview(next.view) guard let pvc = presentingVC else { UIApplication.shared.keyWindow?.rootViewController = next return } self?.dismiss(animated: false) { pvc.present(next, animated: false) } } } } }
apache-2.0
fad50561fafdece290e7cab725f0b941
34.368098
250
0.607632
5.934122
false
false
false
false
Salt7900/belly_codechallenge
DetailViewController.swift
1
1488
// // DetailViewController.swift // belly_cc // // Created by Ben Fallon on 12/16/15. // Copyright © 2015 Ben Fallon. All rights reserved. // import UIKit import MapKit import CoreLocation class DetailViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var locationName: UILabel! @IBOutlet weak var locationDistance: UILabel! @IBOutlet weak var locationType: UILabel! var nameOfLocation: String? var distanceToLocation: Double? var typeOfLocation: String? var locationLat: Double? var locationLong: Double? override func viewDidLoad() { super.viewDidLoad() locationName.text = nameOfLocation locationDistance.text = String("\(distanceToLocation!) miles away") locationType.text = typeOfLocation! setupMap() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.dismissViewControllerAnimated(true, completion: nil) } func setupMap(){ let location = CLLocationCoordinate2D(latitude: locationLat!, longitude: locationLong!) let span = MKCoordinateSpanMake(0.005, 0.005) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = location mapView.addAnnotation(annotation) } }
mit
4a315c30ffa6964500089b84cd43c37d
25.553571
95
0.667787
4.989933
false
false
false
false
Oscareli98/Moya
Demo/DemoTests/RACSignal+MoyaSpec.swift
10
7242
import Quick import Moya import ReactiveCocoa import Nimble @objc class TestClass { } // Necessary since UIImage(named:) doesn't work correctly in the test bundle extension UIImage { class func testPNGImage(named name: String) -> UIImage { let bundle = NSBundle(forClass: TestClass().dynamicType) let path = bundle.pathForResource(name, ofType: "png") return UIImage(contentsOfFile: path!)! } } func signalSendingData(data: NSData, statusCode: Int = 200) -> RACSignal { return RACSignal.createSignal { (subscriber) -> RACDisposable! in subscriber.sendNext(MoyaResponse(statusCode: statusCode, data: data, response: nil)) subscriber.sendCompleted() return nil } } class RACSignalMoyaSpec: QuickSpec { override func spec() { describe("status codes filtering", { it("filters out unrequested status codes") { let data = NSData() let signal = signalSendingData(data, statusCode: 10) var errored = false signal.filterStatusCodes(0...9).subscribeNext({ (object) -> Void in XCTFail("called on non-correct status code: \(object)") }, error: { (error) -> Void in errored = true }) expect(errored).to(beTruthy()) } it("filters out non-successful status codes") { let data = NSData() let signal = signalSendingData(data, statusCode: 404) var errored = false signal.filterSuccessfulStatusCodes().subscribeNext({ (object) -> Void in XCTFail("called on non-success status code: \(object)") }, error: { (error) -> Void in errored = true }) expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = NSData() let signal = signalSendingData(data) var called = false signal.filterSuccessfulStatusCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("filters out non-successful status and redirect codes") { let data = NSData() let signal = signalSendingData(data, statusCode: 404) var errored = false signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext({ (object) -> Void in XCTFail("called on non-success status code: \(object)") }, error: { (error) -> Void in errored = true }) expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = NSData() let signal = signalSendingData(data) var called = false signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("passes through correct redirect codes") { let data = NSData() let signal = signalSendingData(data, statusCode: 304) var called = false signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } }) describe("image maping", { it("maps data representing an image to an image") { let image = UIImage.testPNGImage(named: "testImage") let data = UIImageJPEGRepresentation(image, 0.75) let signal = signalSendingData(data) var size: CGSize? signal.mapImage().subscribeNext { (image) -> Void in size = image.size } expect(size).to(equal(image.size)) } it("ignores invalid data") { let data = NSData() let signal = signalSendingData(data) var receivedError: NSError? signal.mapImage().subscribeNext({ (image) -> Void in XCTFail("next called for invalid data") }, error: { (error) -> Void in receivedError = error }) expect(receivedError?.code).to(equal(MoyaErrorCode.ImageMapping.rawValue)) } }) describe("JSON mapping", { () -> () in it("maps data representing some JSON to that JSON") { let json = ["name": "John Crighton", "occupation": "Astronaut"] let data = NSJSONSerialization.dataWithJSONObject(json, options: nil, error: nil) let signal = signalSendingData(data!) var receivedJSON: [String: String]? signal.mapJSON().subscribeNext { (json) -> Void in if let json = json as? [String: String] { receivedJSON = json } } expect(receivedJSON?["name"]).to(equal(json["name"])) expect(receivedJSON?["occupation"]).to(equal(json["occupation"])) } it("returns a Cocoa error domain for invalid JSON") { let json = "{ \"name\": \"john }" let data = json.dataUsingEncoding(NSUTF8StringEncoding) let signal = signalSendingData(data!) var receivedError: NSError? signal.mapJSON().subscribeNext({ (image) -> Void in XCTFail("next called for invalid data") }, error: { (error) -> Void in receivedError = error }) expect(receivedError).toNot(beNil()) expect(receivedError?.domain).to(equal("\(NSCocoaErrorDomain)")) } }) describe("string mapping", { () -> () in it("maps data representing a string to a string") { let string = "You have the rights to the remains of a silent attorney." let data = string.dataUsingEncoding(NSUTF8StringEncoding) let signal = signalSendingData(data!) var receivedString: String? signal.mapString().subscribeNext { (string) -> Void in receivedString = string as? String return } expect(receivedString).to(equal(string)) } }) } }
mit
b5a5656c2aa5ad6d6886e6a05f2fb23c
37.73262
99
0.484535
6.085714
false
false
false
false
mightydeveloper/swift
stdlib/public/core/StringUTF16.swift
10
9600
//===--- StringUTF16.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// extension String { /// A collection of UTF-16 code units that encodes a `String` value. public struct UTF16View : CollectionType, _Reflectable, CustomStringConvertible, CustomDebugStringConvertible { public struct Index { // Foundation needs access to these fields so it can expose // random access public // SPI(Foundation) init(_offset: Int) { self._offset = _offset } public let _offset: Int } /// The position of the first code unit if the `String` is /// non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return Index(_offset: 0) } /// The "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return Index(_offset: _length) } @warn_unused_result func _toInternalIndex(i: Int) -> Int { return _core.startIndex + _offset + i } /// Access the element at `position`. /// /// - Requires: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(i: Index) -> UTF16.CodeUnit { let position = i._offset _precondition(position >= 0 && position < _length, "out-of-range access on a UTF16View") let index = _toInternalIndex(position) let u = _core[index] if _fastPath((u >> 11) != 0b1101_1) { // Neither high-surrogate, nor low-surrogate -- well-formed sequence // of 1 code unit. return u } if (u >> 10) == 0b1101_10 { // `u` is a high-surrogate. SequenceType is well-formed if it // is followed by a low-surrogate. if _fastPath( index + 1 < _core.count && (_core[index + 1] >> 10) == 0b1101_11) { return u } return 0xfffd } // `u` is a low-surrogate. SequenceType is well-formed if // previous code unit is a high-surrogate. if _fastPath(index != 0 && (_core[index - 1] >> 10) == 0b1101_10) { return u } return 0xfffd } #if _runtime(_ObjC) // These may become less important once <rdar://problem/19255291> is addressed. @available( *, unavailable, message="Indexing a String's UTF16View requires a String.UTF16View.Index, which can be constructed from Int when Foundation is imported") public subscript(i: Int) -> UTF16.CodeUnit { fatalError("unavailable function can't be called") } @available( *, unavailable, message="Slicing a String's UTF16View requires a Range<String.UTF16View.Index>, String.UTF16View.Index can be constructed from Int when Foundation is imported") public subscript(subRange: Range<Int>) -> UTF16View { fatalError("unavailable function can't be called") } #endif /// Access the elements delimited by the given half-open range of /// indices. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(subRange: Range<Index>) -> UTF16View { return UTF16View( _core, offset: _toInternalIndex(subRange.startIndex._offset), length: subRange.endIndex._offset - subRange.startIndex._offset) } internal init(_ _core: _StringCore) { self._offset = 0 self._length = _core.count self._core = _core } internal init(_ _core: _StringCore, offset: Int, length: Int) { self._offset = offset self._length = length self._core = _core } /// Returns a mirror that reflects `self`. @warn_unused_result public func _getMirror() -> _MirrorType { return _UTF16ViewMirror(self) } public var description: String { let start = _toInternalIndex(0) let end = _toInternalIndex(_length) return String(_core[start..<end]) } public var debugDescription: String { return "StringUTF16(\(self.description.debugDescription))" } var _offset: Int var _length: Int let _core: _StringCore } /// A UTF-16 encoding of `self`. public var utf16: UTF16View { return UTF16View(_core) } /// Construct the `String` corresponding to the given sequence of /// UTF-16 code units. If `utf16` contains unpaired surrogates, the /// result is `nil`. public init?(_ utf16: UTF16View) { let wholeString = String(utf16._core) if let start = UTF16Index( _offset: utf16._offset ).samePositionIn(wholeString) { if let end = UTF16Index( _offset: utf16._offset + utf16._length ).samePositionIn(wholeString) { self = wholeString[start..<end] return } } return nil } /// The index type for subscripting a `String`'s `utf16` view. public typealias UTF16Index = UTF16View.Index } // Conformance to RandomAccessIndexType intentionally only appears // when Foundation is loaded extension String.UTF16View.Index : BidirectionalIndexType { public typealias Distance = Int @warn_unused_result public func successor() -> String.UTF16View.Index { return String.UTF16View.Index(_offset: _offset.successor()) } @warn_unused_result public func predecessor() -> String.UTF16View.Index { return String.UTF16View.Index(_offset: _offset.predecessor()) } } @warn_unused_result public func == ( lhs: String.UTF16View.Index, rhs: String.UTF16View.Index ) -> Bool { return lhs._offset == rhs._offset } extension String.UTF16View.Index : Comparable, Equatable {} @warn_unused_result public func < ( lhs: String.UTF16View.Index, rhs: String.UTF16View.Index ) -> Bool { return lhs._offset < rhs._offset } // We can do some things more efficiently, even if we don't promise to // by conforming to RandomAccessIndexType. /// Do not use this operator directly; call distance(start, end) instead. extension String.UTF16View.Index { @warn_unused_result public func distanceTo(end: String.UTF16View.Index) -> String.UTF16View.Index.Distance { return self._offset.distanceTo(end._offset) } @warn_unused_result public func advancedBy(n: Distance) -> String.UTF16View.Index { return String.UTF16View.Index(_offset: self._offset.advancedBy(n)) } @warn_unused_result public func advancedBy(n: Distance, limit: String.UTF16View.Index) -> String.UTF16View.Index { return String.UTF16View.Index( _offset: self._offset.advancedBy(n, limit: limit._offset)) } } // Index conversions extension String.UTF16View.Index { /// Construct the position in `utf16` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// - Requires: `utf8Index` is an element of /// `String(utf16)!.utf8.indices`. public init?( _ utf8Index: String.UTF8Index, within utf16: String.UTF16View ) { let core = utf16._core _precondition( utf8Index._coreIndex >= 0 && utf8Index._coreIndex <= core.endIndex, "Invalid String.UTF8Index for this UTF-16 view") // Detect positions that have no corresponding index. if !utf8Index._isOnUnicodeScalarBoundary { return nil } _offset = utf8Index._coreIndex } /// Construct the position in `utf16` that corresponds exactly to /// `unicodeScalarIndex`. /// /// - Requires: `unicodeScalarIndex` is an element of /// `String(utf16)!.unicodeScalars.indices`. public init( _ unicodeScalarIndex: String.UnicodeScalarIndex, within utf16: String.UTF16View) { _offset = unicodeScalarIndex._position } /// Construct the position in `utf16` that corresponds exactly to /// `characterIndex`. /// /// - Requires: `characterIndex` is an element of /// `String(utf16)!.indices`. public init(_ characterIndex: String.Index, within utf16: String.UTF16View) { _offset = characterIndex._utf16Index } /// Return the position in `utf8` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// - Requires: `self` is an element of /// `String(utf8)!.utf16.indices`. @warn_unused_result public func samePositionIn( utf8: String.UTF8View ) -> String.UTF8View.Index? { return String.UTF8View.Index(self, within: utf8) } /// Return the position in `unicodeScalars` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// - Requires: `self` is an element of /// `String(unicodeScalars).utf16.indices`. @warn_unused_result public func samePositionIn( unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarIndex? { return String.UnicodeScalarIndex(self, within: unicodeScalars) } /// Return the position in `characters` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// - Requires: `self` is an element of `characters.utf16.indices`. @warn_unused_result public func samePositionIn( characters: String ) -> String.Index? { return String.Index(self, within: characters) } }
apache-2.0
38ed749e9366c73a2d0a9d0523a73496
30.270358
166
0.646667
3.975155
false
false
false
false
marcelobns/Photobooth
PhotoboothiOS/PreviewViewController.swift
1
2765
import Foundation import UIKit import MobileCoreServices import TwitterKit class PreviewViewController: BoothViewController, UITextViewDelegate { @IBOutlet weak var previewImage: UIImageView! @IBOutlet weak var tweetTxt: UITextView! override func viewDidLoad() { super.viewDidLoad() super.setupNav(true, enableSettings : false) // get image from photo let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String let destinationPath = documentsPath.stringByAppendingPathComponent("photobooth.jpg") let image = UIImage(contentsOfFile: destinationPath ) previewImage.image = image var tap = UITapGestureRecognizer(target:self, action:Selector("share")) self.view.addGestureRecognizer(tap) var swipe = UISwipeGestureRecognizer(target: self, action: Selector("reset")) self.view.addGestureRecognizer(swipe) tweetTxt.text = SettingsViewController.Settings.tweetText tweetTxt.becomeFirstResponder(); tweetTxt.alpha = 0.6 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } @IBAction func didTouchTweetButton(sender: AnyObject) { self.share() } func share(){ let status = tweetTxt.text let uiImage = self.previewImage.image let composer = TWTRComposer() composer.setText(status) composer.setImage(uiImage) composer.showWithCompletion { (result) -> Void in if (result == TWTRComposerResult.Cancelled) { self.showCamera() } else { println("Sending tweet!") sleep(3) self.showTweets() } } println("share") } func reset(){ self.showCamera() println("reset") } func showCamera() { self.navigationController?.popViewControllerAnimated(true) // self.performSegueWithIdentifier("camera", sender: self); } func showTweets(){ dispatch_async(dispatch_get_main_queue(), { let controller = TweetViewController() self.showViewController(controller, sender: self) }); } func showSettings() { dispatch_async(dispatch_get_main_queue(), { let controller = self.storyboard!.instantiateViewControllerWithIdentifier("SettingsViewController") as! UIViewController self.showViewController(controller, sender: self) }); } }
mit
62af8a6334e632ecd546c93e73dc5c14
27.802083
132
0.599638
5.772443
false
false
false
false
BeckWang0912/GesturePasswordKit
GesturePasswordKit/GesturePassword/LockInfoView.swift
1
1462
// // LockInfoView.swift // GesturePasswordKit // // Created by Beck.Wang on 2017/5/14. // Copyright © 2017年 Beck. All rights reserved. // import UIKit class LockInfoView: UIView { fileprivate var itemViews = [LockItemView]() init(frame: CGRect, options: LockOptions) { super.init(frame: frame) backgroundColor = options.backgroundColor for _ in 0 ..< 9 { let itemView = LockItemView(options: options) itemViews.append(itemView) addSubview(itemView) } } func showSelectedItems(_ passwordStr: String) { for char in passwordStr { itemViews[Int("\(char)")!].selected = true } } func resetItems() { itemViews.forEach { $0.selected = false } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let marginV: CGFloat = 3 let rectWH = (frame.width - marginV * 2) / 3 for (idx, subview) in subviews.enumerated() { let row = CGFloat(idx % 3) let col = CGFloat(idx / 3) let rectX = (rectWH + marginV) * row let rectY = (rectWH + marginV) * col let rect = CGRect(x: rectX, y: rectY, width: rectWH, height: rectWH) subview.tag = idx subview.frame = rect } } }
mit
365c0bd175368aaac1a58b4609d9652d
25.053571
80
0.559287
4.144886
false
false
false
false
aestesis/Aether
Sources/Aether/Foundation/Thread.swift
1
1911
// // Thread.swift // Aether // // Created by renan jegouzo on 03/03/2016. // Copyright © 2016 aestesis. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation public class Thread : Atom { var nst:Foundation.Thread? init(nst:Foundation.Thread) { self.nst=nst } static var current:Thread { if let t=Foundation.Thread.current.threadDictionary["aestesis.alib.Thread"] as? Thread { return t; } let t=Thread(nst:Foundation.Thread.current) Foundation.Thread.current.threadDictionary["aestesis.alib.Thread"]=t return t } var dictionary=[String:Any]() subscript(key: String) -> Any? { get { return dictionary[key] } set(v) { dictionary[key]=v } } public static func sleep(_ seconds:Double) { Foundation.Thread.sleep(forTimeInterval: TimeInterval(seconds)) } public static var callstack : [String] { return Foundation.Thread.callStackSymbols } public init(_ fn:@escaping ()->()) { super.init() nst=Foundation.Thread { fn() } nst!.start() } public func cancel() { if let t=nst, !t.isCancelled { t.cancel() } } public var cancelled : Bool { if let t=nst { return t.isCancelled } return true } }
apache-2.0
a19f773d909ae60a5045304ec95ac0ed
28.84375
96
0.626178
3.938144
false
false
false
false
jopamer/swift
test/SILGen/protocol_resilience.swift
2
17443
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -module-name protocol_resilience -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift // RUN: %target-swift-emit-silgen -module-name protocol_resilience -I %t -enable-sil-ownership -enable-resilience %s | %FileCheck %s import resilient_protocol prefix operator ~~~ infix operator <*> infix operator <**> infix operator <===> public protocol P {} // Protocol is public -- needs resilient witness table public protocol ResilientMethods { associatedtype AssocType : P func defaultWitness() func anotherDefaultWitness(_ x: Int) -> Self func defaultWitnessWithAssociatedType(_ a: AssocType) func defaultWitnessMoreAbstractThanRequirement(_ a: AssocType, b: Int) func defaultWitnessMoreAbstractThanGenericRequirement<T>(_ a: AssocType, t: T) func noDefaultWitness() func defaultWitnessIsNotPublic() static func staticDefaultWitness(_ x: Int) -> Self } extension ResilientMethods { // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientMethodsP14defaultWitnessyyF // CHECK-LABEL: sil @$S19protocol_resilience16ResilientMethodsPAAE14defaultWitnessyyF public func defaultWitness() {} // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientMethodsP21anotherDefaultWitnessyxSiF // CHECK-LABEL: sil @$S19protocol_resilience16ResilientMethodsPAAE21anotherDefaultWitnessyxSiF public func anotherDefaultWitness(_ x: Int) -> Self {} // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypeyy05AssocI0QzF // CHECK-LABEL: sil @$S19protocol_resilience16ResilientMethodsPAAE32defaultWitnessWithAssociatedTypeyy05AssocI0QzF public func defaultWitnessWithAssociatedType(_ a: AssocType) {} // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirement_1by9AssocTypeQz_SitF // CHECK-LABEL: sil @$S19protocol_resilience16ResilientMethodsPAAE41defaultWitnessMoreAbstractThanRequirement_1byqd___qd_0_tr0_lF public func defaultWitnessMoreAbstractThanRequirement<A, T>(_ a: A, b: T) {} // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirement_1ty9AssocTypeQz_qd__tlF // CHECK-LABEL: sil @$S19protocol_resilience16ResilientMethodsPAAE48defaultWitnessMoreAbstractThanGenericRequirement_1tyqd___qd_0_tr0_lF public func defaultWitnessMoreAbstractThanGenericRequirement<A, T>(_ a: A, t: T) {} // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientMethodsP20staticDefaultWitnessyxSiFZ // CHECK-LABEL: sil @$S19protocol_resilience16ResilientMethodsPAAE20staticDefaultWitnessyxSiFZ public static func staticDefaultWitness(_ x: Int) -> Self {} // CHECK-LABEL: sil private @$S19protocol_resilience16ResilientMethodsPAAE25defaultWitnessIsNotPublic{{.*}}F private func defaultWitnessIsNotPublic() {} } public protocol ResilientConstructors { init(noDefault: ()) init(default: ()) init?(defaultIsOptional: ()) init?(defaultNotOptional: ()) init(optionalityMismatch: ()) } extension ResilientConstructors { // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience21ResilientConstructorsP7defaultxyt_tcfC // CHECK-LABEL: sil @$S19protocol_resilience21ResilientConstructorsPAAE7defaultxyt_tcfC public init(default: ()) { self.init(noDefault: ()) } // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience21ResilientConstructorsP17defaultIsOptionalxSgyt_tcfC // CHECK-LABEL: sil @$S19protocol_resilience21ResilientConstructorsPAAE17defaultIsOptionalxSgyt_tcfC public init?(defaultIsOptional: ()) { self.init(noDefault: ()) } // CHECK-LABEL: sil @$S19protocol_resilience21ResilientConstructorsPAAE20defaultIsNotOptionalxyt_tcfC public init(defaultIsNotOptional: ()) { self.init(noDefault: ()) } // CHECK-LABEL: sil @$S19protocol_resilience21ResilientConstructorsPAAE19optionalityMismatchxSgyt_tcfC public init?(optionalityMismatch: ()) { self.init(noDefault: ()) } } public protocol ResilientStorage { associatedtype T : ResilientConstructors var propertyWithDefault: Int { get } var propertyWithNoDefault: Int { get } var mutablePropertyWithDefault: Int { get set } var mutablePropertyNoDefault: Int { get set } var mutableGenericPropertyWithDefault: T { get set } subscript(x: T) -> T { get set } var mutatingGetterWithNonMutatingDefault: Int { mutating get set } } extension ResilientStorage { // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP19propertyWithDefaultSivg // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAE19propertyWithDefaultSivg public var propertyWithDefault: Int { get { return 0 } } // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivg // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSivg // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivs // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSivs // CHECK-LABEL: sil private [transparent] @$S19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivmytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivm public var mutablePropertyWithDefault: Int { get { return 0 } set { } } public private(set) var mutablePropertyNoDefault: Int { get { return 0 } set { } } // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvg // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzvg // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvs // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzvs // CHECK-LABEL: sil private [transparent] @$S19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvmytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvm public var mutableGenericPropertyWithDefault: T { get { return T(default: ()) } set { } } // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStoragePy1TQzAEcig // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAEy1TQzAEcig // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStoragePy1TQzAEcis // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAEy1TQzAEcis // CHECK-LABEL: sil private [transparent] @$S19protocol_resilience16ResilientStoragePy1TQzAEcimytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStoragePy1TQzAEcim public subscript(x: T) -> T { get { return x } set { } } // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivg // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSivg // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivs // CHECK-LABEL: sil @$S19protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSivs // CHECK-LABEL: sil private [transparent] @$S19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivmytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivm public var mutatingGetterWithNonMutatingDefault: Int { get { return 0 } set { } } } public protocol ResilientOperators { associatedtype AssocType : P static prefix func ~~~(s: Self) static func <*><T>(s: Self, t: T) static func <**><T>(t: T, s: Self) -> AssocType static func <===><T : ResilientOperators>(t: T, s: Self) -> T.AssocType } // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience18ResilientOperatorsP3tttopyyxFZ // CHECK-LABEL: sil @$S19protocol_resilience3tttopyyxlF public prefix func ~~~<S>(s: S) {} // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience18ResilientOperatorsP3lmgoiyyx_qd__tlFZ // CHECK-LABEL: sil @$S19protocol_resilience3lmgoiyyq__xtr0_lF public func <*><T, S>(s: S, t: T) {} // Swap the generic parameters to make sure we don't mix up our DeclContexts // when mapping interface types in and out // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience18ResilientOperatorsP4lmmgoiy9AssocTypeQzqd___xtlFZ // CHECK-LABEL: sil @$S19protocol_resilience4lmmgoiy9AssocTypeQzq__xtAA18ResilientOperatorsRzr0_lF public func <**><S : ResilientOperators, T>(t: T, s: S) -> S.AssocType {} // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience18ResilientOperatorsP5leeegoiy9AssocTypeQyd__qd___xtAaBRd__lFZ // CHECK-LABEL: sil @$S19protocol_resilience5leeegoiy9AssocTypeQzx_q_tAA18ResilientOperatorsRzAaER_r0_lF public func <===><T : ResilientOperators, S : ResilientOperators>(t: T, s: S) -> T.AssocType {} public protocol ReabstractSelfBase { // No requirements } public protocol ReabstractSelfRefined : class, ReabstractSelfBase { // A requirement with 'Self' abstracted as a class instance var callback: (Self) -> Self { get set } } func id<T>(_ t: T) -> T {} extension ReabstractSelfBase { // A witness for the above requirement, but with 'Self' maximally abstracted public var callback: (Self) -> Self { get { return id } nonmutating set { } } } // CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvg : $@convention(witness_method: ReabstractSelfRefined) <τ_0_0 where τ_0_0 : ReabstractSelfRefined> (@guaranteed τ_0_0) -> @owned @callee_guaranteed (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $τ_0_0 // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value %0 : $τ_0_0 // CHECK-NEXT: store [[SELF_COPY]] to [init] [[SELF_BOX]] : $*τ_0_0 // CHECK: [[WITNESS:%.*]] = function_ref @$S19protocol_resilience18ReabstractSelfBasePAAE8callbackyxxcvg // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS]]<τ_0_0>([[SELF_BOX]]) // CHECK: [[THUNK_FN:%.*]] = function_ref @$SxxIegnr_xxIeggo_19protocol_resilience21ReabstractSelfRefinedRzlTR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<τ_0_0>([[RESULT]]) // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[THUNK]] final class X : ReabstractSelfRefined {} func inoutFunc(_ x: inout Int) {} // CHECK-LABEL: sil hidden @$S19protocol_resilience22inoutResilientProtocolyy010resilient_A005OtherdE0_pzF func inoutResilientProtocol(_ x: inout OtherResilientProtocol) { // CHECK: function_ref @$S18resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivm inoutFunc(&x.propertyInExtension) } struct OtherConformingType : OtherResilientProtocol {} // CHECK-LABEL: sil hidden @$S19protocol_resilience22inoutResilientProtocolyyAA19OtherConformingTypeVzF func inoutResilientProtocol(_ x: inout OtherConformingType) { // CHECK: function_ref @$S18resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivm inoutFunc(&x.propertyInExtension) // CHECK: function_ref @$S18resilient_protocol22OtherResilientProtocolPAAE25staticPropertyInExtensionSivmZ inoutFunc(&OtherConformingType.staticPropertyInExtension) } // CHECK-LABEL: sil_default_witness_table P { // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientMethods { // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientMethods.defaultWitness!1: {{.*}} : @$S19protocol_resilience16ResilientMethodsP14defaultWitnessyyF // CHECK-NEXT: method #ResilientMethods.anotherDefaultWitness!1: {{.*}} : @$S19protocol_resilience16ResilientMethodsP21anotherDefaultWitnessyxSiF // CHECK-NEXT: method #ResilientMethods.defaultWitnessWithAssociatedType!1: {{.*}} : @$S19protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypeyy05AssocI0QzF // CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanRequirement!1: {{.*}} : @$S19protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirement_1by9AssocTypeQz_SitF // CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanGenericRequirement!1: {{.*}} : @$S19protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirement_1ty9AssocTypeQz_qd__tlF // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientMethods.staticDefaultWitness!1: {{.*}} : @$S19protocol_resilience16ResilientMethodsP20staticDefaultWitnessyxSiFZ // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientConstructors { // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @$S19protocol_resilience21ResilientConstructorsP7defaultxyt_tcfC // CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @$S19protocol_resilience21ResilientConstructorsP17defaultIsOptionalxSgyt_tcfC // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientStorage { // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientStorage.propertyWithDefault!getter.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP19propertyWithDefaultSivg // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!getter.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivg // CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!setter.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivs // CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!materializeForSet.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivm // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!getter.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvg // CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!setter.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvs // CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!materializeForSet.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvm // CHECK-NEXT: method #ResilientStorage.subscript!getter.1: {{.*}} : @$S19protocol_resilience16ResilientStoragePy1TQzAEcig // CHECK-NEXT: method #ResilientStorage.subscript!setter.1: {{.*}} : @$S19protocol_resilience16ResilientStoragePy1TQzAEcis // CHECK-NEXT: method #ResilientStorage.subscript!materializeForSet.1: {{.*}} : @$S19protocol_resilience16ResilientStoragePy1TQzAEcim // CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!getter.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivg // CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!setter.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivs // CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!materializeForSet.1: {{.*}} : @$S19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivm // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientOperators { // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientOperators."~~~"!1: {{.*}} : @$S19protocol_resilience18ResilientOperatorsP3tttopyyxFZ // CHECK-NEXT: method #ResilientOperators."<*>"!1: {{.*}} : @$S19protocol_resilience18ResilientOperatorsP3lmgoiyyx_qd__tlFZ // CHECK-NEXT: method #ResilientOperators."<**>"!1: {{.*}} : @$S19protocol_resilience18ResilientOperatorsP4lmmgoiy9AssocTypeQzqd___xtlFZ // CHECK-NEXT: method #ResilientOperators."<===>"!1: {{.*}} : @$S19protocol_resilience18ResilientOperatorsP5leeegoiy9AssocTypeQyd__qd___xtAaBRd__lFZ // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ReabstractSelfRefined { // CHECK-NEXT: no_default // CHECK-NEXT: method #ReabstractSelfRefined.callback!getter.1: {{.*}} : @$S19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvg // CHECK-NEXT: method #ReabstractSelfRefined.callback!setter.1: {{.*}} : @$S19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvs // CHECK-NEXT: method #ReabstractSelfRefined.callback!materializeForSet.1: {{.*}} : @$S19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvm // CHECK-NEXT: }
apache-2.0
4721415714950841c82027e4108a568d
53.820755
296
0.786726
4.425743
false
false
false
false
gouyz/GYZBaking
baking/Classes/Orders/Controller/GYZOrderInfoVC.swift
1
15420
// // GYZOrderInfoVC.swift // baking // 订单控制器 // Created by gouyz on 2017/3/29. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD private let orderInfoCell = "orderInfoCell" private let orderInfoHeader = "orderInfoHeader" private let orderInfoFooter = "orderInfoFooter" class GYZOrderInfoVC: GYZBaseVC,UITableViewDelegate,UITableViewDataSource,GYZOrderFooterViewDelegate { /// 状态0全部 1未支付 2待收货 3交易成功 var orderStatus : Int? var currPage : Int = 1 var orderInfoModels: [GYZOrderInfoModel] = [GYZOrderInfoModel]() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(UIEdgeInsets.init(top: 0, left: 0, bottom: kTitleAndStateHeight, right: 0)) } requestOrderListData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// 懒加载UITableView lazy var tableView : UITableView = { let table = UITableView(frame: CGRect.zero, style: .grouped) table.dataSource = self table.delegate = self table.tableFooterView = UIView() table.separatorColor = kGrayLineColor table.register(GYZOrderCell.self, forCellReuseIdentifier: orderInfoCell) table.register(GYZOrderHeaderView.self, forHeaderFooterViewReuseIdentifier: orderInfoHeader) table.register(GYZOrderFooterView.self, forHeaderFooterViewReuseIdentifier: orderInfoFooter) weak var weakSelf = self ///添加下拉刷新 GYZTool.addPullRefresh(scorllView: table, pullRefreshCallBack: { weakSelf?.refresh() }) ///添加上拉加载更多 GYZTool.addLoadMore(scorllView: table, loadMoreCallBack: { weakSelf?.loadMore() }) return table }() ///获取商品数据 func requestOrderListData(){ weak var weakSelf = self showLoadingView() GYZNetWork.requestNetwork("Order/orderList",parameters: ["type": orderStatus ?? 0,"p":currPage,"user_id":userDefaults.string(forKey: "userId") ?? ""], success: { (response) in weakSelf?.hiddenLoadingView() weakSelf?.closeRefresh() // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 let data = response["result"] guard let info = data["info"].array else { return } for item in info{ guard let itemInfo = item.dictionaryObject else { return } let model = GYZOrderInfoModel.init(dict: itemInfo) weakSelf?.orderInfoModels.append(model) } if weakSelf?.orderInfoModels.count > 0{ weakSelf?.hiddenEmptyView() weakSelf?.tableView.reloadData() }else{ ///显示空页面 weakSelf?.showEmptyView(content: "暂无订单信息,请点击刷新", reload: { weakSelf?.refresh() weakSelf?.hiddenEmptyView() }) } }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hiddenLoadingView() weakSelf?.closeRefresh() GYZLog(error) if weakSelf?.currPage == 1{//第一次加载失败,显示加载错误页面 weakSelf?.showEmptyView(content: "加载失败,请点击重新加载", reload: { weakSelf?.refresh() weakSelf?.hiddenEmptyView() }) } }) } // MARK: - 上拉加载更多/下拉刷新 /// 下拉刷新 func refresh(){ currPage = 1 requestOrderListData() } /// 上拉加载更多 func loadMore(){ currPage += 1 requestOrderListData() } /// 关闭上拉/下拉刷新 func closeRefresh(){ if tableView.mj_header.isRefreshing(){//下拉刷新 orderInfoModels.removeAll() GYZTool.endRefresh(scorllView: tableView) }else if tableView.mj_footer.isRefreshing(){//上拉加载更多 GYZTool.endLoadMore(scorllView: tableView) } } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return orderInfoModels.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orderInfoModels[section].goods_list!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: orderInfoCell) as! GYZOrderCell let model = orderInfoModels[indexPath.section] cell.dataModel = model.goods_list?[indexPath.row] cell.selectionStyle = .none return cell } ///MARK : UITableViewDelegate func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: orderInfoHeader) as! GYZOrderHeaderView headerView.dataModel = orderInfoModels[section] return headerView } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: orderInfoFooter) as! GYZOrderFooterView footerView.contentView.backgroundColor = kWhiteColor footerView.delegate = self footerView.dataModel = orderInfoModels[section] return footerView } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return kTitleHeight } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailsVC = GYZOrderDetailaVC() detailsVC.orderId = orderInfoModels[indexPath.section].order_id! navigationController?.pushViewController(detailsVC, animated: true) } ///MARK: GYZOrderFooterViewDelegate func didClickedOperate(index: Int, orderId: String) { if index == 100 {//待付款 -去结算 goPayVC(orderId: orderId) }else if index == 101{//已付款 showCancleOrder(orderId: orderId) }else if index == 103{//货到付款 }else if index == 104{//确认收货 showReceivedGoods(orderId: orderId) }else if index == 105{//已签收 }else if index == 102{//已取消 }else if index == 106{//已退款 }else if index == 107{//去评价 var orderInfo: GYZOrderInfoModel? for item in orderInfoModels { if item.order_id == orderId { orderInfo = item break } } if orderInfo?.is_comment == "1" {//0未评价,1已评价 return } let conmentVC = GYZConmentVC() conmentVC.orderId = orderId conmentVC.shopId = (orderInfo?.member_info?.member_id)! conmentVC.shopName = (orderInfo?.member_info?.company_name)! navigationController?.pushViewController(conmentVC, animated: true) }else if index == 108{//不接单 } } /// 收货 /// /// - Parameter orderId: func showReceivedGoods(orderId: String){ var orderInfo: GYZOrderInfoModel? for item in orderInfoModels { if item.order_id == orderId { orderInfo = item break } } if orderInfo?.goods_list?.count > 1 { GYZAlertViewTools.alertViewTools.showSheet(title: nil, message: nil, cancleTitle: "取消", titleArray: ["全部收货","部分收货"], viewController: self) { [weak self](index) in if index == 0{//全部收货 self?.showAlert(orderId: orderId) }else if index == 1 {//部分收货 self?.goReceivedGoodsVC(orderId: orderId) } } }else{//只有1个商品,直接收货 showAlert(orderId: orderId) } } /// 取消订单 /// /// - Parameter orderId: func showCancleOrder(orderId: String){ weak var weakSelf = self GYZAlertViewTools.alertViewTools.showAlert(title: "提示", message: "确定取消订单吗?", cancleTitle: "取消", viewController: self, buttonTitles: "确定") { (index) in if index != -1{ //取消订单 weakSelf?.requestCancleOrder(orderId: orderId) } } } ////提示是否确定收货 func showAlert(orderId: String){ weak var weakSelf = self GYZAlertViewTools.alertViewTools.showAlert(title: "提示", message: "确定收货吗?", cancleTitle: "取消", viewController: self, buttonTitles: "确定") { (index) in if index != -1{ //确定收货 weakSelf?.requestUpdateStatusOrder(orderId: orderId) } } } /// 选择收货商品 /// /// - Parameter orderId: func goReceivedGoodsVC(orderId: String){ let receivedGoodsVC = GYZSelectReceivedGoodsVC() receivedGoodsVC.orderId = orderId receivedGoodsVC.type = "0" navigationController?.pushViewController(receivedGoodsVC, animated: true) } /// 去支付 /// /// - Parameter orderId: <#orderId description#> func goPayVC(orderId: String){ var orderInfo: GYZOrderInfoModel? for item in orderInfoModels { if item.order_id == orderId { orderInfo = item break } } let payVC = GYZPayVC() payVC.orderId = orderId payVC.orderNo = (orderInfo?.order_number)! payVC.orderPrice = (orderInfo?.order_price)! payVC.payPrice = (orderInfo?.pay_price)! payVC.eventName = (orderInfo?.event_name)! payVC.originalPrice = (orderInfo?.original_price)! payVC.useBalance = (orderInfo?.use_balance)! navigationController?.pushViewController(payVC, animated: true) } /// 删除订单 /// /// - Parameter orderId: func didClickedDeleteOrder(orderId: String) { weak var weakSelf = self GYZAlertViewTools.alertViewTools.showAlert(title: "提示", message: "确定删除订单吗?", cancleTitle: "取消", viewController: self, buttonTitles: "确定") { (index) in if index != -1{ //确定删除订单 weakSelf?.requestDeleteOrder(orderId: orderId) } } } /// 删除订单 /// /// - Parameter orderId: func requestDeleteOrder(orderId: String){ weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("Order/del", parameters: ["order_id":orderId], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 ///刷新列表 for (x,item) in (weakSelf?.orderInfoModels.enumerated())! { if item.order_id == orderId{ weakSelf?.orderInfoModels.remove(at: x) break } } if weakSelf?.orderInfoModels.count > 0 { weakSelf?.tableView.reloadData() }else{ weakSelf?.showEmptyView(content:"暂无订单信息") } } MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } /// 确认收货 /// /// - Parameter orderId: func requestUpdateStatusOrder(orderId: String){ weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("Order/confirm", parameters: ["order_id":orderId], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 ///刷新列表 for item in (weakSelf?.orderInfoModels)! { if item.order_id == orderId{ //状态变为交易成功 item.status = "7" break } } weakSelf?.tableView.reloadData() } MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } /// 取消订单 /// /// - Parameter orderId: func requestCancleOrder(orderId: String){ weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("Order/cancelOrder", parameters: ["order_id":orderId,"user_id":userDefaults.string(forKey: "userId") ?? ""], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 ///刷新列表 for item in (weakSelf?.orderInfoModels)! { if item.order_id == orderId{ //状态变为交易成功 item.status = "2" break } } weakSelf?.tableView.reloadData() } MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } }
mit
63177d0163d0b7a1de8d79edaaa1f357
32.85977
184
0.542739
5.037278
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressShareExtension/ShareTagsPickerViewController.swift
1
17248
import Foundation import CocoaLumberjack import WordPressShared class ShareTagsPickerViewController: UIViewController { // MARK: - Public Properties @objc var onValueChanged: ((String) -> Void)? // MARK: - Private Properties /// Tags originally passed into init() /// fileprivate let originalTags: [String] /// SiteID to fetch tags for /// fileprivate let siteID: Int /// Apply Bar Button /// fileprivate lazy var applyButton: UIBarButtonItem = { let applyTitle = NSLocalizedString("Apply", comment: "Apply action on the app extension tags picker screen. Saves the selected tags for the post.") let button = UIBarButtonItem(title: applyTitle, style: .plain, target: self, action: #selector(applyWasPressed)) button.accessibilityIdentifier = "Apply Button" return button }() /// Cancel Bar Button /// fileprivate lazy var cancelButton: UIBarButtonItem = { let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel action on the app extension tags picker screen.") let button = UIBarButtonItem(title: cancelTitle, style: .plain, target: self, action: #selector(cancelWasPressed)) button.accessibilityIdentifier = "Cancel Button" return button }() @objc fileprivate let keyboardObserver = TableViewKeyboardObserver() fileprivate let textView = UITextView() fileprivate let textViewContainer = UIView() fileprivate let tableView = UITableView(frame: .zero, style: .grouped) fileprivate var dataSource: PostTagPickerDataSource = LoadingDataSource() { didSet { tableView.dataSource = dataSource reloadTableData() } } // MARK: - Initializers init(siteID: Int, tags: String?) { self.originalTags = tags?.arrayOfTags() ?? [] self.siteID = siteID super.init(nibName: nil, bundle: nil) textView.text = normalizeInitialTags(tags: originalTags) textViewDidChange(textView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Initialize Interface setupNavigationBar() setupTableView() setupTextView() setupConstraints() keyboardObserver.tableView = tableView } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateSuggestions() textView.becomeFirstResponder() loadTags() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.stopEditing() }) } // MARK: - Setup Helpers fileprivate func setupNavigationBar() { navigationItem.hidesBackButton = true navigationItem.leftBarButtonItem = cancelButton navigationItem.rightBarButtonItem = applyButton } fileprivate func setupTableView() { WPStyleGuide.configureColors(view: view, tableView: tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: SuggestionsDataSource.cellIdentifier) tableView.register(LoadingDataSource.Cell.self, forCellReuseIdentifier: LoadingDataSource.cellIdentifier) tableView.register(FailureDataSource.Cell.self, forCellReuseIdentifier: FailureDataSource.cellIdentifier) tableView.delegate = self tableView.dataSource = dataSource tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude)) reloadTableData() } fileprivate func setupTextView() { textView.delegate = self textView.autocorrectionType = .yes textView.autocapitalizationType = .none textView.font = WPStyleGuide.tableviewTextFont() textView.textColor = .neutral(.shade70) textView.isScrollEnabled = false textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = UIEdgeInsets(top: Constants.textViewTopBottomInset, left: 0, bottom: Constants.textViewTopBottomInset, right: 0) textViewContainer.backgroundColor = UIColor(light: .white, dark: .listBackground) textViewContainer.layer.masksToBounds = false } fileprivate func setupConstraints() { view.addSubview(tableView) textViewContainer.addSubview(textView) view.addSubview(textViewContainer) textView.translatesAutoresizingMaskIntoConstraints = false textViewContainer.translatesAutoresizingMaskIntoConstraints = false tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ textView.topAnchor.constraint(equalTo: textViewContainer.topAnchor), textView.bottomAnchor.constraint(equalTo: textViewContainer.bottomAnchor), textView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor), textView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor), textViewContainer.topAnchor.constraint(equalTo: view.topAnchor, constant: 0), textViewContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Constants.textContainerLeadingConstant), textViewContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: Constants.textContainerTrailingConstant), textViewContainer.bottomAnchor.constraint(equalTo: tableView.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) } } // MARK: - Actions extension ShareTagsPickerViewController { @objc func cancelWasPressed() { stopEditing() _ = navigationController?.popViewController(animated: true) } @objc func applyWasPressed() { stopEditing() let tags = allTags if originalTags != tags { onValueChanged?(tags.joined(separator: ", ")) } _ = navigationController?.popViewController(animated: true) } func suggestionTapped(cell: UITableViewCell?) { guard let tag = cell?.textLabel?.text else { return } complete(tag: tag) } } // MARK: - Tags Loading fileprivate extension ShareTagsPickerViewController { func loadTags() { dataSource = LoadingDataSource() let service = AppExtensionsService() service.fetchTopTagsForSite(siteID, onSuccess: { tags in let tagNames = tags.compactMap { return $0.name } self.tagsLoaded(tags: tagNames) }) { error in self.tagsFailedLoading(error: error) } } func tagsLoaded(tags: [String]) { dataSource = SuggestionsDataSource(suggestions: tags, selectedTags: completeTags, searchQuery: partialTag) } func tagsFailedLoading(error: Error?) { if let error = error { DDLogError("Error loading tags: \(error)") } dataSource = FailureDataSource() } } // MARK: - Tag tokenization /* There are two different "views" of the tag list: 1. For completion purposes, everything before the last comma is a "completed" tag, and will not appear again in suggestions. The text after the last comma (or the whole text if there is no comma) will be interpreted as a partially typed tag (parialTag) and used to filter suggestions. 2. The above doesn't apply when it comes to reporting back the tag list, and so we use `allTags` for all the tags in the text view. In this case the last part of text is considered as a complete tag as well. */ private extension ShareTagsPickerViewController { var tagsInField: [String] { return textView.text.arrayOfTags() } var partialTag: String { return tagsInField.last ?? "" } var completeTags: [String] { return Array(tagsInField.dropLast()) } var allTags: [String] { return tagsInField.filter({ !$0.isEmpty }) } func complete(tag: String) { var tags = completeTags tags.append(tag) tags.append("") textView.text = tags.joined(separator: ", ") updateSuggestions() } } // MARK: - Text & Input Handling extension ShareTagsPickerViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { guard textView.markedTextRange == nil else { // Don't try to normalize if we're still in multistage input return } normalizeText() updateSuggestions() } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let original = textView.text as NSString if range.length == 0, range.location == original.length, text == ",", partialTag.isEmpty { // Don't allow a second comma if the last tag is blank return false } else if range.length == 1 && text == "", // Deleting last character range.location > 0, // Not at the beginning range.location + range.length == original.length, // At the end original.substring(with: NSRange(location: range.location - 1, length: 1)) == "," // Previous is a comma { // Delete the comma as well textView.text = original.substring(to: range.location - 1) + original.substring(from: range.location + range.length) textView.selectedRange = NSRange(location: range.location - 1, length: 0) textViewDidChange(textView) return false } else if range.length == 0, // Inserting text == ",", // a comma range.location == original.length // at the end { // Append a space textView.text = original.replacingCharacters(in: range, with: ", ") textViewDidChange(textView) return false } else if text == "\n", // return range.location == original.length, // at the end !partialTag.isEmpty // with some (partial) tag typed { textView.text = original.replacingCharacters(in: range, with: ", ") textViewDidChange(textView) return false } else if text == "\n" // return anywhere else { return false } return true } fileprivate func normalizeText() { // Remove any space before a comma, and allow one space at most after. let regexp = try! NSRegularExpression(pattern: "\\s*(,(\\s|(\\s(?=\\s)))?)\\s*", options: []) let text = textView.text ?? "" let range = NSRange(location: 0, length: (text as NSString).length) textView.text = regexp.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "$1") } /// Normalize tags for initial set up. /// /// The algorithm here differs slightly as we don't want to interpret the last tag as a partial one. /// fileprivate func normalizeInitialTags(tags: [String]) -> String { var tags = tags.filter({ !$0.isEmpty }) tags.append("") return tags.joined(separator: ", ") } func updateSuggestions() { dataSource.selectedTags = completeTags dataSource.searchQuery = partialTag reloadTableData() } } // MARK: - UITableView Delegate Conformance extension ShareTagsPickerViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch tableView.dataSource { case is FailureDataSource: loadTags() case is LoadingDataSource: return case is SuggestionsDataSource: suggestionTapped(cell: tableView.cellForRow(at: indexPath)) default: assertionFailure("Unexpected data source") } } } // MARK: - Misc private helpers fileprivate extension ShareTagsPickerViewController { func stopEditing() { view.endEditing(true) resetPresentationViewUsingKeyboardFrame() } func resetPresentationViewUsingKeyboardFrame(_ keyboardFrame: CGRect = .zero) { guard let presentationController = navigationController?.presentationController as? ExtensionPresentationController else { return } presentationController.resetViewUsingKeyboardFrame(keyboardFrame) } func reloadTableData() { tableView.reloadData() textViewContainer.layer.shadowOpacity = tableView.isEmpty ? 0 : 0.5 } } // MARK: - Data Sources private protocol PostTagPickerDataSource: UITableViewDataSource { var selectedTags: [String] { get set } var searchQuery: String { get set } } private class LoadingDataSource: NSObject, PostTagPickerDataSource { @objc var selectedTags = [String]() @objc var searchQuery = "" @objc static let cellIdentifier = "Loading" typealias Cell = UITableViewCell func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: LoadingDataSource.cellIdentifier, for: indexPath) WPStyleGuide.Share.configureLoadingTagCell(cell) cell.textLabel?.text = NSLocalizedString("Loading...", comment: "Loading tags") cell.selectionStyle = .none return cell } } private class FailureDataSource: NSObject, PostTagPickerDataSource { @objc var selectedTags = [String]() @objc var searchQuery = "" @objc static let cellIdentifier = "Failure" typealias Cell = UITableViewCell func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: FailureDataSource.cellIdentifier, for: indexPath) WPStyleGuide.Share.configureLoadingTagCell(cell) cell.textLabel?.text = NSLocalizedString("Couldn't load tags. Tap to retry.", comment: "Error message when tag loading failed") return cell } } private class SuggestionsDataSource: NSObject, PostTagPickerDataSource { @objc static let cellIdentifier = "Default" @objc let suggestions: [String] @objc init(suggestions: [String], selectedTags: [String], searchQuery: String) { self.suggestions = suggestions self.selectedTags = selectedTags self.searchQuery = searchQuery super.init() } @objc var selectedTags: [String] @objc var searchQuery: String @objc var availableSuggestions: [String] { return suggestions.filter({ !selectedTags.contains($0) }) } @objc var matchedSuggestions: [String] { guard !searchQuery.isEmpty else { return availableSuggestions } return availableSuggestions.filter({ $0.localizedStandardContains(searchQuery) }) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return matchedSuggestions.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SuggestionsDataSource.cellIdentifier, for: indexPath) WPStyleGuide.Share.configureTagCell(cell) let match = matchedSuggestions[indexPath.row] cell.textLabel?.attributedText = highlight(searchQuery, in: match) return cell } @objc func highlight(_ search: String, in string: String) -> NSAttributedString { let highlighted = NSMutableAttributedString(string: string) let range = (string as NSString).localizedStandardRange(of: search) guard range.location != NSNotFound else { return highlighted } let font = UIFont.systemFont(ofSize: WPStyleGuide.tableviewTextFont().pointSize, weight: .bold) highlighted.setAttributes([.font: font], range: range) return highlighted } } // MARK: - Constants extension ShareTagsPickerViewController { struct Constants { static let textViewTopBottomInset: CGFloat = 11.0 static let textContainerLeadingConstant: CGFloat = -1 static let textContainerTrailingConstant: CGFloat = 1 } }
gpl-2.0
a94f03d96733932cd060d773e116f59e
35.159329
155
0.66599
5.209302
false
false
false
false
ivlevAstef/DITranquillity
Sources/Core/API/DIScope.swift
1
2017
// // DIScope.swift // DITranquillity // // Created by Alexander Ivlev on 12/02/2019. // Copyright © 2019 Alexander Ivlev. All rights reserved. // /// Scopes need for control lifetime of your objects public class DIScope { /// Scope name. Used in logging public let name: String internal var policy: DILifeTime.ReferenceCounting internal var storage: DIStorage /// Make Scope. Scopes need for control lifetime of your objects /// /// - Parameters: /// - name: Scope name. need for logging /// - storage: data storing policy /// - policy: weak or strong. For weak policy DI wrapped objects use Weak class and save wrapped objects into storage. /// - parent: Checks the parent scope before making an object public init(name: String, storage: DIStorage, policy: DILifeTime.ReferenceCounting = .strong, parent: DIScope? = nil) { self.name = name self.policy = policy if let parentStorage = parent?.storage { self.storage = DICompositeStorage(storages: [storage, parentStorage]) } else { self.storage = storage } } /// Remove all saved objects public func clean() { self.storage.clean() } internal func toWeak() { if policy == .weak { return } let weakStorage = DIUnsafeCacheStorage() for (key, value) in storage.any { weakStorage.save(object: WeakAny(value: value), by: key) } policy = .weak storage = weakStorage } internal func toStrongCopy() -> DIScope { let strongStorage = DIUnsafeCacheStorage() for (key, value) in storage.any { if let weakRef = value as? WeakAny { if let value = weakRef.value { strongStorage.save(object: value, by: key) } } else { strongStorage.save(object: value, by: key) } } return DIScope(name: name, storage: strongStorage, policy: .strong, parent: nil) } } extension DIScope: CustomStringConvertible { public var description: String { return "<Scope. name: \(name)>" } }
mit
e5fc7e1ee63dca334c39c69b57d8735f
26.243243
122
0.655258
3.960707
false
false
false
false
Nemanja92/SwiftPlaygrounds
SwiftPlayground.playground/Pages/abstractRetalionship.xcplaygroundpage/Contents.swift
1
2081
import Foundation // Protocols protocol Boy { associatedtype RingType func impress() func propose(with ring: RingType) } protocol Smart { func tellSmartThings() } protocol Pretty { func smile() } // Procotol extensions extension Smart { func tellSmartThings() { print("What if I tell you 1+1=3?") } } extension Pretty { func smile() { print("☺️") } } extension Boy { func propose(with ring: RingType) { print("Will you marry me?") } } // Structs struct Ring {} struct SmartBoy: Boy, Smart { typealias RingType = Ring func impress() { tellSmartThings() } } struct PrettyBoy: Boy, Pretty { typealias RingType = Ring func impress() { smile() } } struct PerfectBoy: Boy, Smart, Pretty { typealias RingType = Ring func impress() { smile() tellSmartThings() } } protocol Girl { associatedtype Partner func date(_ partner: Partner) } struct SmartGirl: Girl { func date(_ partner: AnySmartBoy<Ring>) { // kisses, tea, and so on... :P } } struct PrettyGirl<B: Boy & Pretty>: Girl { func date(_ partner: B) { // kisses, tea, and so on... :P } } // Type erasure /* Create a concerete type conformin to Boy & Smart Inject the abstract type Store the functions Redirect calls to stored functions */ struct AnySmartBoy<R>: Boy, Smart { typealias RingType = R private let _impress: (Void) -> Void private let _propose: (R) -> Void init<B: Boy & Smart>(_ erased: B) where B.RingType == R { _impress = erased.impress _propose = erased.propose } func impress() { _impress() } func propose(with ring: R) { _propose(ring) } } // Boys let john = SmartBoy() let tom = PrettyBoy() let matt = PerfectBoy() // Girls let emma = SmartGirl() let kate = PrettyGirl<PrettyBoy>() // Relationships emma.date(AnySmartBoy(john)) emma.date(AnySmartBoy(matt)) //kate.date(tom) //kate.date(matt)
mit
674e16295ee94d6b422b970f54ed353d
15.354331
61
0.595571
3.438742
false
false
false
false
vimeo/VimeoNetworking
Sources/Shared/Core/URLEncoding.swift
1
6538
// // URLEncoding.swift // VimeoNetworking // // Created by Rogerio de Paula Assis on 9/2/19. // Copyright © 2019 Vimeo. All rights reserved. // import Foundation /// The dictionary of parameters for a given `URLRequest`. public typealias Parameters = [String: Any] /// The type used to create a URL encoded string of parameters to be appended to the request URL. /// For URL requests with a non-nil HTTP body, the content type is set to /// `application/x-www-form-urlencoded; charset=utf-8` /// /// Collection types are encoded using the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`). /// For dictionary values, the key surrounded by square brackets is used (`foo[bar]=baz`). public struct URLEncoding: ParameterEncoding { public enum Destination { case methodDependent case URL case body } /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// MARK: - Private /// The destination to which parameters will be encoded to private let destination: Destination /// The URLEncoding type public initializer /// - Parameter destination: the destination to which parameters will be encoded to. Defaults to `methodDependent` public init(destination: Destination = .methodDependent) { self.destination = destination } /// Creates a URL request by encoding parameters and adding them to an existing request. /// /// - Parameters: /// - requestConvertible: a type that can be converted to a URL request /// - parameters: the parameters to encode /// /// - Returns: the encoded URLRequest instance /// - Throws: an error if the encoding process fails. public func encode(_ requestConvertible: URLRequestConvertible, with parameters: Any?) throws -> URLRequest { var urlRequest = try requestConvertible.asURLRequest() guard let unwrappedParameters = parameters as? Parameters else { if parameters == nil { // NO-OP - just return the original, unmodified request return urlRequest } // Couldn't cast to Parameters so we bail with an error throw VimeoNetworkingError.encodingFailed(.invalidParameters) } if unwrappedParameters.count == 0 { // NO-OP - just return the original, unmodified request return urlRequest } let rawMethod = urlRequest.httpMethod ?? "" guard let httpMethod = HTTPMethod(rawValue: rawMethod) else { throw VimeoNetworkingError.encodingFailed(.missingHTTPMethod) } switch (self.destination, httpMethod) { // .get, .head and .delete methods take their encoded parameters directly in the URL unless otherwise specified case (.methodDependent, .get), (.methodDependent, .head), (.methodDependent, .delete), (.URL, _): return try inURLEncode(unwrappedParameters, for: &urlRequest) case (.methodDependent, _), (.body, _): return try bodyEncode(unwrappedParameters, for: &urlRequest) } } private func inURLEncode(_ parameters: Parameters, for urlRequest: inout URLRequest) throws -> URLRequest { guard let url = urlRequest.url else { throw VimeoNetworkingError.encodingFailed(.missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { // Ensure we retain any existing query parameters, and append an `&` at the end, then the parameters to encode let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(forParameters: parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } return urlRequest } private func bodyEncode(_ parameters: Parameters, for urlRequest: inout URLRequest) throws -> URLRequest { // For body encoding we ensure the content-type header is set correctly if urlRequest.value(forHTTPHeaderField: .contentTypeHeaderField) == nil { urlRequest.setValue(.contentTypeFormUrlEncodedHeaderValue, forHTTPHeaderField: .contentTypeHeaderField) } urlRequest.httpBody = query(forParameters: parameters).data(using: .utf8, allowLossyConversion: false) return urlRequest } } // MARK: - Private convenience utilities private extension URLEncoding { func query(forParameters parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: "\(key)[]", value: value) } } else if let bool = value as? Bool { let boolString = bool ? "1" : "0" components.append((key.escaped, boolString.escaped)) } else { components.append((key.escaped, "\(value)".escaped)) } return components } } private extension String { var escaped: String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") return addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? self } } /// Constants private extension String { static let contentTypeHeaderField = "Content-Type" static let contentTypeFormUrlEncodedHeaderValue = "application/x-www-form-urlencoded; charset=utf-8" }
mit
a251e5073927a8ac44ae2814f06aa0da
39.602484
122
0.63806
5.135114
false
false
false
false
kaojohnny/CoreStore
CoreStoreTests/IntoTests.swift
1
7290
// // IntoTests.swift // CoreStore // // Copyright © 2016 John Rommel Estropia // // 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 XCTest @testable import CoreStore //MARK: - IntoTests final class IntoTests: XCTestCase { @objc dynamic func test_ThatIntoClauseConstants_AreCorrect() { XCTAssertEqual(Into<NSManagedObject>.defaultConfigurationName, "PF_DEFAULT_CONFIGURATION_NAME") } @objc dynamic func test_ThatIntoClauses_ConfigureCorrectly() { do { let into = Into() XCTAssert(into.entityClass === NSManagedObject.self) XCTAssertNil(into.configuration) XCTAssertTrue(into.inferStoreIfPossible) } do { let into = Into<TestEntity1>() XCTAssert(into.entityClass === TestEntity1.self) XCTAssertNil(into.configuration) XCTAssertTrue(into.inferStoreIfPossible) } do { let into = Into(TestEntity1) XCTAssert(into.entityClass === TestEntity1.self) XCTAssertNil(into.configuration) XCTAssertTrue(into.inferStoreIfPossible) } do { let into = Into(TestEntity1.self as AnyClass) XCTAssert(into.entityClass === TestEntity1.self) XCTAssertNil(into.configuration) XCTAssertTrue(into.inferStoreIfPossible) } do { let into = Into<TestEntity1>("Config1") XCTAssert(into.entityClass === TestEntity1.self) XCTAssertEqual(into.configuration, "Config1") XCTAssertFalse(into.inferStoreIfPossible) } do { let into = Into(TestEntity1.self, "Config1") XCTAssert(into.entityClass === TestEntity1.self) XCTAssertEqual(into.configuration, "Config1") XCTAssertFalse(into.inferStoreIfPossible) } do { let into = Into(TestEntity1.self as AnyClass, "Config1") XCTAssert(into.entityClass === TestEntity1.self) XCTAssertEqual(into.configuration, "Config1") XCTAssertFalse(into.inferStoreIfPossible) } } @objc dynamic func test_ThatIntoClauses_AreEquatable() { do { let into = Into() XCTAssertEqual(into, Into()) XCTAssertEqual(into, Into<NSManagedObject>()) XCTAssertEqual(into, Into(NSManagedObject.self as AnyClass)) XCTAssertFalse(into == Into<TestEntity1>()) XCTAssertNotEqual(into, Into<NSManagedObject>("Config1")) } do { let into = Into<TestEntity1>() XCTAssertEqual(into, Into(TestEntity1)) XCTAssertEqual(into, Into(TestEntity1.self as AnyClass)) XCTAssertFalse(into == Into<TestEntity2>()) XCTAssertNotEqual(into, Into<TestEntity1>("Config1")) } do { let into = Into(TestEntity1) XCTAssertEqual(into, Into<TestEntity1>()) XCTAssertEqual(into, Into(TestEntity1.self as AnyClass)) XCTAssertFalse(into == Into<TestEntity2>()) XCTAssertNotEqual(into, Into<TestEntity1>("Config1")) } do { let into = Into(TestEntity1.self as AnyClass) XCTAssert(into == Into<TestEntity1>()) XCTAssertEqual(into, Into(TestEntity1)) XCTAssertFalse(into == Into<TestEntity2>()) XCTAssertFalse(into == Into<TestEntity1>("Config1")) } do { let into = Into<TestEntity1>("Config1") XCTAssertEqual(into, Into(TestEntity1.self, "Config1")) XCTAssertEqual(into, Into(TestEntity1.self as AnyClass, "Config1")) XCTAssertFalse(into == Into<TestEntity2>("Config1")) XCTAssertNotEqual(into, Into<TestEntity1>("Config2")) } do { let into = Into(TestEntity1.self, "Config1") XCTAssertEqual(into, Into(TestEntity1.self, "Config1")) XCTAssertEqual(into, Into<TestEntity1>("Config1")) XCTAssertFalse(into == Into<TestEntity2>("Config1")) XCTAssertNotEqual(into, Into<TestEntity1>("Config2")) } do { let into = Into(TestEntity1.self as AnyClass, "Config1") XCTAssert(into == Into<TestEntity1>("Config1")) XCTAssertEqual(into, Into(TestEntity1.self, "Config1")) XCTAssertFalse(into == Into<TestEntity2>("Config1")) XCTAssertFalse(into == Into<TestEntity1>("Config2")) } } @objc dynamic func test_ThatIntoClauses_BridgeCorrectly() { do { let into = Into() let objcInto = into.bridgeToObjectiveC XCTAssertEqual(into, objcInto.bridgeToSwift) } do { let into = Into<TestEntity1>() let objcInto = into.bridgeToObjectiveC XCTAssertTrue(into == objcInto.bridgeToSwift) } do { let into = Into(TestEntity1.self as AnyClass) let objcInto = into.bridgeToObjectiveC XCTAssertEqual(into, objcInto.bridgeToSwift) } do { let into = Into(TestEntity1.self as AnyClass) let objcInto = into.bridgeToObjectiveC XCTAssertEqual(into, objcInto.bridgeToSwift) } do { let into = Into<TestEntity1>("Config1") let objcInto = into.bridgeToObjectiveC XCTAssertTrue(into == objcInto.bridgeToSwift) } do { let into = Into(TestEntity1.self, "Config1") let objcInto = into.bridgeToObjectiveC XCTAssertTrue(into == objcInto.bridgeToSwift) } do { let into = Into(TestEntity1.self as AnyClass, "Config1") let objcInto = into.bridgeToObjectiveC XCTAssertTrue(into == objcInto.bridgeToSwift) } } }
mit
f9dc4235b19ec3c4bb2effa032d67ac7
34.730392
103
0.589244
5.082985
false
true
false
false
robrix/Hammer.swift
Hammer/Box.swift
1
1063
// Copyright (c) 2014 Rob Rix. All rights reserved. /// Boxes \c value up for use in recursive structs/enums or parameterized classes. /// /// This is a currently-required implementation detail to handle the compiler’s lack of codegen for recursive enum/struct definitions, and classes with non-fixed layout. func box<T>(value: T) -> Box<T> { return Box(value) } /// A box for a value which would otherwise because you can’t have recursive enum/struct definitions. OnHeap could be used if we could produce an ObjectIdentifier or otherwise make it Identifiable. class Box<T> { let value: T init(_ value: T) { self.value = value } func __conversion() -> T { return value } } extension Box : Identifiable { var identity: ObjectIdentifier { return reflect(self).objectIdentifier! } } func == <Boxed : Equatable>(a: Box<Boxed>, b: Box<Boxed>) -> Bool { return a.value == b.value } func hash<Boxed : Hashable>(box: Box<Boxed>) -> Int { return box.value.hashValue } func toString<T>(box: Box<T>) -> String { return toString(box.value) }
mit
30e0f9c6ffa9387d1021e022dacd8bb1
24.829268
197
0.705382
3.518272
false
false
false
false
crossroadlabs/Twist
Sources/Twist/ObservableSignals.swift
1
2048
//===--- ObservableSignals.swift ----------------------------------------------===// //Copyright (c) 2016 Crossroad Labs s.r.o. // //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 ExecutionContext import Event public extension SignalNodeProtocol { public func bind<Component : ExecutionContextTenantProtocol, Observable : ParametrizableMutableObservableProtocol>(to component: Component, on pd: PropertyDescriptor<Component, Observable>) -> Off where Observable.Payload == Payload { let prop = pd.makeProperty(for: component) let forthOff = self.pour(to: prop) let backOff = prop.pour(to: self) return { forthOff() backOff() } } } public extension SignalStreamProtocol { public func pour<Component : ExecutionContextTenantProtocol, Observable : ParametrizableMutableObservableProtocol>(to component: Component, on pd: PropertyDescriptor<Component, Observable>) -> Off where Observable.Payload == Payload { let prop = pd.makeProperty(for: component) return self.pour(to: prop) } } public extension SignalEndpoint { public func subscribe<Component : ExecutionContextTenantProtocol, Observable : ParametrizableObservableProtocol>(to component: Component, on pd: PropertyDescriptor<Component, Observable>) -> Off where Observable.Payload == Payload { return pd.makeProperty(for: component).pour(to: self) } }
apache-2.0
333a76d7d056bd4996817db777252fec
41.666667
238
0.681152
4.807512
false
false
false
false
ul7290/realm-cocoa
Realm/Tests/Swift2.0/SwiftObjectInterfaceTests.swift
1
11178
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import Realm import Foundation class OuterClass { class InnerClass { } } class SwiftStringObjectSubclass : SwiftStringObject { var stringCol2 = "" } class SwiftSelfRefrencingSubclass: SwiftStringObject { dynamic var objects = RLMArray(objectClassName: SwiftSelfRefrencingSubclass.className()) } class SwiftDefaultObject: RLMObject { dynamic var intCol = 1 dynamic var boolCol = true override class func defaultPropertyValues() -> [NSObject : AnyObject]? { return ["intCol": 2] } } class SwiftOptionalNumberObject: RLMObject { dynamic var intCol: NSNumber? = 1 dynamic var floatCol: NSNumber? = 2.2 as Float dynamic var doubleCol: NSNumber? = 3.3 as Double dynamic var boolCol: NSNumber? = true } class SwiftObjectInterfaceTests: RLMTestCase { // Swift models func testSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() let obj = SwiftObject() realm.addObject(obj) obj.boolCol = true obj.intCol = 1234 obj.floatCol = 1.1 obj.doubleCol = 2.2 obj.stringCol = "abcd" obj.binaryCol = "abcd".dataUsingEncoding(NSUTF8StringEncoding) obj.dateCol = NSDate(timeIntervalSince1970: 123) obj.objectCol = SwiftBoolObject() obj.objectCol.boolCol = true obj.arrayCol.addObject(obj.objectCol) try! realm.commitWriteTransaction() let data = NSString(string: "abcd").dataUsingEncoding(NSUTF8StringEncoding) let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, true, "should be true") XCTAssertEqual(firstObj.intCol, 1234, "should be 1234") XCTAssertEqual(firstObj.floatCol, Float(1.1), "should be 1.1") XCTAssertEqual(firstObj.doubleCol, 2.2, "should be 2.2") XCTAssertEqual(firstObj.stringCol, "abcd", "should be abcd") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 123), "should be epoch + 123") XCTAssertEqual(firstObj.objectCol.boolCol, true, "should be true") XCTAssertEqual(obj.arrayCol.count, UInt(1), "array count should be 1") XCTAssertEqual((obj.arrayCol.firstObject() as? SwiftBoolObject)!.boolCol, true, "should be true") } func testDefaultValueSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() realm.addObject(SwiftObject()) try! realm.commitWriteTransaction() let data = NSString(string: "a").dataUsingEncoding(NSUTF8StringEncoding) let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, false, "should be false") XCTAssertEqual(firstObj.intCol, 123, "should be 123") XCTAssertEqual(firstObj.floatCol, Float(1.23), "should be 1.23") XCTAssertEqual(firstObj.doubleCol, 12.3, "should be 12.3") XCTAssertEqual(firstObj.stringCol, "a", "should be a") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 1), "should be epoch + 1") XCTAssertEqual(firstObj.objectCol.boolCol, false, "should be false") XCTAssertEqual(firstObj.arrayCol.count, UInt(0), "array count should be zero") } func testMergedDefaultValuesSwiftObject() { let realm = self.realmWithTestPath() realm.beginWriteTransaction() SwiftDefaultObject.createInRealm(realm, withValue: NSDictionary()) try! realm.commitWriteTransaction() let object = SwiftDefaultObject.allObjectsInRealm(realm).firstObject() as! SwiftDefaultObject XCTAssertEqual(object.intCol, 2, "defaultPropertyValues should override native property default value") XCTAssertEqual(object.boolCol, true, "native property default value should be used if defaultPropertyValues doesn't contain that key") } func testSubclass() { // test className methods XCTAssertEqual("SwiftStringObject", SwiftStringObject.className()) XCTAssertEqual("SwiftStringObjectSubclass", SwiftStringObjectSubclass.className()) let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() SwiftStringObject.createInDefaultRealmWithValue(["string"]) SwiftStringObjectSubclass.createInDefaultRealmWithValue(["string", "string2"]) try! realm.commitWriteTransaction() // ensure creation in proper table XCTAssertEqual(UInt(1), SwiftStringObjectSubclass.allObjects().count) XCTAssertEqual(UInt(1), SwiftStringObject.allObjects().count) try! realm.transactionWithBlock { // create self referencing subclass let sub = SwiftSelfRefrencingSubclass.createInDefaultRealmWithValue(["string", []]) let sub2 = SwiftSelfRefrencingSubclass() sub.objects.addObject(sub2) } } func testOptionalNSNumberProperties() { let realm = realmWithTestPath() let no = SwiftOptionalNumberObject() XCTAssertEqual([.Int, .Float, .Double, .Bool], no.objectSchema.properties.map { $0.type }) XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(true, no.boolCol!) try! realm.transactionWithBlock { realm.addObject(no) no.intCol = nil no.floatCol = nil no.doubleCol = nil no.boolCol = nil } XCTAssertNil(no.intCol) XCTAssertNil(no.floatCol) XCTAssertNil(no.doubleCol) XCTAssertNil(no.boolCol) try! realm.transactionWithBlock { no.intCol = 1.1 no.floatCol = 2.2 as Float no.doubleCol = 3.3 no.boolCol = false } XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(false, no.boolCol!) } func testOptionalSwiftProperties() { let realm = realmWithTestPath() try! realm.transactionWithBlock { realm.addObject(SwiftOptionalObject()) } let firstObj = SwiftOptionalObject.allObjectsInRealm(realm).firstObject() as! SwiftOptionalObject XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) try! realm.transactionWithBlock { firstObj.optObjectCol = SwiftBoolObject() firstObj.optObjectCol!.boolCol = true firstObj.optStringCol = "Hi!" firstObj.optBinaryCol = NSData(bytes: "hi", length: 2) firstObj.optDateCol = NSDate(timeIntervalSinceReferenceDate: 10) } XCTAssertTrue(firstObj.optObjectCol!.boolCol) XCTAssertEqual(firstObj.optStringCol!, "Hi!") XCTAssertEqual(firstObj.optBinaryCol!, NSData(bytes: "hi", length: 2)) XCTAssertEqual(firstObj.optDateCol!, NSDate(timeIntervalSinceReferenceDate: 10)) try! realm.transactionWithBlock { firstObj.optObjectCol = nil firstObj.optStringCol = nil firstObj.optBinaryCol = nil firstObj.optDateCol = nil } XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) } func testSwiftClassNameIsDemangled() { XCTAssertEqual(SwiftObject.className(), "SwiftObject", "Calling className() on Swift class should return demangled name") } // Objective-C models // Note: Swift doesn't support custom accessor names // so we test to make sure models with custom accessors can still be accessed func testCustomAccessors() { let realm = realmWithTestPath() realm.beginWriteTransaction() let ca = CustomAccessorsObject.createInRealm(realm, withValue: ["name", 2]) XCTAssertEqual(ca.name!, "name", "name property should be name.") ca.age = 99 XCTAssertEqual(ca.age, Int32(99), "age property should be 99") try! realm.commitWriteTransaction() } func testClassExtension() { let realm = realmWithTestPath() realm.beginWriteTransaction() let bObject = BaseClassStringObject() bObject.intCol = 1 bObject.stringCol = "stringVal" realm.addObject(bObject) try! realm.commitWriteTransaction() let objectFromRealm = BaseClassStringObject.allObjectsInRealm(realm)[0] as! BaseClassStringObject XCTAssertEqual(objectFromRealm.intCol, Int32(1), "Should be 1") XCTAssertEqual(objectFromRealm.stringCol!, "stringVal", "Should be stringVal") } func testCreateOrUpdate() { let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithValue(["string", 1]) let objects = SwiftPrimaryStringObject.allObjects(); XCTAssertEqual(objects.count, UInt(1), "Should have 1 object"); XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 1, "Value should be 1"); SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithValue(["stringCol": "string2", "intCol": 2]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithValue(["string", 3]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 3, "Value should be 3"); try! realm.commitWriteTransaction() } // if this fails (and you haven't changed the test module name), the checks // for swift class names and the demangling logic need to be updated func testNSStringFromClassDemangledTopLevelClassNames() { XCTAssertEqual(NSStringFromClass(OuterClass), "Tests.OuterClass") } // if this fails (and you haven't changed the test module name), the prefix // check in RLMSchema initialization needs to be updated func testNestedClassNameMangling() { XCTAssertEqual(NSStringFromClass(OuterClass.InnerClass.self), "_TtCC5Tests10OuterClass10InnerClass") } }
apache-2.0
8c0d2459306369813bc60be33feb4642
38.779359
142
0.675971
5.0625
false
true
false
false
Takanu/Pelican
Sources/Pelican/API/Request/Request+EditMessage.swift
1
4519
// // Request+Edit.swift // PelicanTests // // Created by Takanu Kyriako on 10/07/2017. // // import Foundation /** Adds an extension that deals in creating requests for editing messages in a chat. */ extension TelegramRequest { /** Builds and returns a TelegramRequest for the API method with the given arguments. ## API Description Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. */ public static func editMessageText(chatID: String?, messageID: Int?, inlineMessageID: Int?, text: String, markup: MarkupType?, parseMode: MessageParseMode = .markdown, disableWebPreview: Bool = false) -> TelegramRequest { let request = TelegramRequest() if chatID != nil { request.query["chat_id"] = Int(chatID!) } if messageID != nil { request.query["message_id"] = messageID } if inlineMessageID != nil { request.query["inline_message_id"] = inlineMessageID } // Check whether any other query needs to be added request.query["text"] = text if markup != nil { if let text = TelegramRequest.encodeMarkupTypeToUTF8(markup!) { request.query["reply_markup"] = text } } if parseMode != .none { request.query["parse_mode"] = parseMode.rawValue } // Set the query request.method = "editMessageText" request.content = text as Any return request } /** Builds and returns a TelegramRequest for the API method with the given arguments. ## API Description Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. */ public static func editMessageCaption(chatID: String, messageID: Int = 0, caption: String, markup: MarkupType?) -> TelegramRequest { let request = TelegramRequest() request.query = [ "chat_id": Int(chatID), "caption": caption, ] // Check whether any other query needs to be added if messageID != 0 { request.query["message_id"] = messageID } if markup != nil { if let text = TelegramRequest.encodeMarkupTypeToUTF8(markup!) { request.query["reply_markup"] = text } } // Set the query request.method = "editMessageCaption" request.content = caption as Any return request } /** Builds and returns a TelegramRequest for the API method with the given arguments. ## API Description Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. */ public static func editMessageReplyMarkup(chatID: String, messageID: Int = 0, inlineMessageID: Int = 0, markup: MarkupType?) -> TelegramRequest { let request = TelegramRequest() request.query = [ "chat_id": Int(chatID), ] // Check whether any other query needs to be added if messageID != 0 { request.query["message_id"] = messageID } if inlineMessageID != 0 { request.query["inline_message_id"] = inlineMessageID } if markup != nil { if let text = TelegramRequest.encodeMarkupTypeToUTF8(markup!) { request.query["reply_markup"] = text } } // Set the query request.method = "editMessageReplyMarkup" request.content = markup as Any return request } /** Builds and returns a TelegramRequest for the API method with the given arguments. ## API Description Use this method to delete a message, including service messages, with the following limitations: - A message can only be deleted if it was sent less than 48 hours ago. - Bots can delete outgoing messages in groups and supergroups. - Bots granted can_post_messages permissions can delete outgoing messages in channels. - If the bot is an administrator of a group, it can delete any message there. - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. Returns True on success. */ public static func deleteMessage(chatID: String, messageID: Int) -> TelegramRequest { let request = TelegramRequest() request.query = [ "chat_id": Int(chatID), "message_id": messageID ] // Set the query request.method = "deleteMessage" return request } }
mit
c6618b12bda2e9135a2e79ceb892b83b
29.328859
207
0.689533
4.045658
false
false
false
false
ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-core
src/ios/CDVBMSClient.swift
1
4450
/* Copyright 2015 IBM Corp. 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 BMSCore @objc(CDVBMSClient) @objcMembers class CDVBMSClient : CDVPlugin { func initialize(_ command: CDVInvokedUrlCommand) { #if swift(>=3.0) self.commandDelegate!.run(inBackground: { guard let region = command.arguments[0] as? String else { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: CustomErrorMessages.invalidRoute) // call success callback self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) return } let client = BMSClient.sharedInstance; //use category to handle objective-c exception client.initialize(bluemixAppRoute: "", bluemixAppGUID: "", bluemixRegion: region) let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "") // call success callback self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) }) #else self.commandDelegate.runInBackground({ guard let region = command.arguments[0] as? String else { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: CustomErrorMessages.invalidRoute) // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) return } let client = BMSClient.sharedInstance; //use category to handle objective-c exception client.initialize(bluemixAppRoute: "", bluemixAppGUID: "", bluemixRegion: region) let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: "") // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) }) #endif } func getBluemixAppRoute(_ command: CDVInvokedUrlCommand) { #if swift(>=3.0) self.commandDelegate!.run(inBackground: { let client = BMSClient.sharedInstance let backendRoute: String = client.bluemixAppRoute! let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: backendRoute) // call success callback self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) }) #else self.commandDelegate!.runInBackground({ let client = BMSClient.sharedInstance let backendRoute: String = client.bluemixAppRoute! let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: backendRoute) // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) }) #endif } func getBluemixAppGUID(_ command: CDVInvokedUrlCommand) { #if swift(>=3.0) self.commandDelegate!.run(inBackground: { let client = BMSClient.sharedInstance let backendGUID: String = client.bluemixAppGUID! let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: backendGUID) // call success callback self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) }) #else self.commandDelegate!.runInBackground({ let client = BMSClient.sharedInstance let backendGUID: String = client.bluemixAppGUID! let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: backendGUID) // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) }) #endif } }
apache-2.0
e28e313f8c78fb0e5fa16fd02c968c44
38.732143
133
0.653933
5.62579
false
false
false
false
ls1intum/sReto
Source/sRetoTests/DummyBrowser.swift
1
2499
// // DummyBrowser.swift // sReto // // Created by Julian Asamer on 17/09/14. // Copyright (c) 2014 - 2016 Chair for Applied Software Engineering // // Licensed under the MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness // for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, // whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. // import Foundation class DummyBrowser: NSObject, Browser { let networkInterface: DummyNetworkInterface var browserDelegate: BrowserDelegate? var isBrowsing: Bool = false var addresses: [UUID: DummyAddress] = [:] init(networkInterface: DummyNetworkInterface) { self.networkInterface = networkInterface } func startBrowsing() { self.networkInterface.register(browser: self) self.isBrowsing = true DispatchQueue.main.async { if let delegate = self.browserDelegate { delegate.didStartBrowsing(self) } } } func stopBrowsing() { self.networkInterface.unregister(browser: self) self.isBrowsing = false DispatchQueue.main.async { if let delegate = self.browserDelegate { delegate.didStopBrowsing(self) } } } func onAddPeer(identifier: UUID, address: DummyAddress) { addresses[identifier] = address self.browserDelegate?.didDiscoverAddress(self, address: address, identifier: identifier) } func onRemovePeer(identifier: UUID) { self.browserDelegate?.didRemoveAddress(self, address: addresses[identifier]!, identifier: identifier) addresses[identifier] = nil } }
mit
2b9519fd57da93a39ac70c3f7d52a227
44.436364
159
0.720288
4.560219
false
false
false
false
ostatnicky/kancional-ios
Pods/BonMot/Sources/Platform.swift
1
2935
// // Platform.swift // BonMot // // Created by Brian King on 9/22/16. // Copyright © 2016 Raizlabs. All rights reserved. // #if os(OSX) import AppKit public typealias BONColor = NSColor public typealias BONImage = NSImage public typealias BONTextField = NSTextField public typealias BONFont = NSFont public typealias BONFontDescriptor = NSFontDescriptor public typealias BONSymbolicTraits = NSFontDescriptor.SymbolicTraits let BONFontDescriptorFeatureSettingsAttribute = NSFontDescriptor.AttributeName.featureSettings let BONFontFeatureTypeIdentifierKey = NSFontDescriptor.FeatureKey.typeIdentifier let BONFontFeatureSelectorIdentifierKey = NSFontDescriptor.FeatureKey.selectorIdentifier #else import UIKit public typealias BONColor = UIColor public typealias BONImage = UIImage public typealias BONFont = UIFont public typealias BONFontDescriptor = UIFontDescriptor public typealias BONSymbolicTraits = UIFontDescriptorSymbolicTraits let BONFontDescriptorFeatureSettingsAttribute = UIFontDescriptor.AttributeName.featureSettings let BONFontFeatureTypeIdentifierKey = UIFontDescriptor.FeatureKey.featureIdentifier let BONFontFeatureSelectorIdentifierKey = UIFontDescriptor.FeatureKey.typeIdentifier #if os(iOS) || os(tvOS) public typealias BONTextField = UITextField #endif #endif public typealias StyleAttributes = [NSAttributedStringKey: Any] #if os(iOS) || os(tvOS) public typealias BonMotTextStyle = UIFontTextStyle public typealias BonMotContentSizeCategory = UIContentSizeCategory #endif // This key is defined here because it needs to be used in non-adaptive code. public let BonMotTransformationsAttributeName = NSAttributedStringKey("BonMotTransformations") extension BONSymbolicTraits { #if os(iOS) || os(tvOS) || os(watchOS) static var italic: BONSymbolicTraits { return .traitItalic } static var bold: BONSymbolicTraits { return .traitBold } static var expanded: BONSymbolicTraits { return .traitExpanded } static var condensed: BONSymbolicTraits { return .traitCondensed } static var vertical: BONSymbolicTraits { return .traitVertical } static var uiOptimized: BONSymbolicTraits { return .traitUIOptimized } static var tightLineSpacing: BONSymbolicTraits { return .traitTightLeading } static var looseLineSpacing: BONSymbolicTraits { return .traitLooseLeading } #else static var uiOptimized: BONSymbolicTraits { return .UIOptimized } static var tightLineSpacing: BONSymbolicTraits { return .tightLeading } static var looseLineSpacing: BONSymbolicTraits { return .looseLeading } #endif }
mit
3f21d0b3287a1036e1d5da92b05e0306
33.517647
98
0.714042
5.775591
false
false
false
false
emesde/cordova-plugin-geofence
src/ios/GeofencePlugin.swift
1
19870
// // GeofencePlugin.swift // ionic-geofence // // Created by tomasz on 07/10/14. // // import Foundation import AudioToolbox import WebKit let TAG = "GeofencePlugin" let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1) typealias Callback = ([[String:String]]?) -> Void func log(message: String){ NSLog("%@ - %@", TAG, message) } func log(messages: [String]) { for message in messages { log(message); } } func log(errors: [[String:String]]) { for error in errors { log("\(error["code"]) - \(error["message"])"); } } func checkRequirements() -> (Bool, [String], [[String:String]]) { var errors = [[String:String]]() var warnings = [String]() if (!CLLocationManager.isMonitoringAvailableForClass(CLRegion)) { errors.append([ "code": GeofencePlugin.ERROR_GEOFENCE_NOT_AVAILABLE, "message": "Geofencing not available" ]) } if (!CLLocationManager.locationServicesEnabled()) { errors.append([ "code": GeofencePlugin.ERROR_LOCATION_SERVICES_DISABLED, "message": "Locationservices disabled" ]) } let authStatus = CLLocationManager.authorizationStatus() if (authStatus != CLAuthorizationStatus.AuthorizedAlways) { errors.append([ "code": GeofencePlugin.ERROR_PERMISSION_DENIED, "message": "Location always permissions not granted" ]) } if (iOS8) { if let notificationSettings = UIApplication.sharedApplication().currentUserNotificationSettings() { if notificationSettings.types == .None { errors.append([ "code": GeofencePlugin.ERROR_PERMISSION_DENIED, "message": "Notification permission missing" ]) } else { if !notificationSettings.types.contains(.Sound) { warnings.append("Warning: notification settings - sound permission missing") } if !notificationSettings.types.contains(.Alert) { warnings.append("Warning: notification settings - alert permission missing") } if !notificationSettings.types.contains(.Badge) { warnings.append("Warning: notification settings - badge permission missing") } } } else { errors.append([ "code": GeofencePlugin.ERROR_PERMISSION_DENIED, "message": "Notification permission missing" ]) } } let ok = (errors.count == 0) return (ok, warnings, errors) } @available(iOS 8.0, *) @objc(HWPGeofencePlugin) class GeofencePlugin : CDVPlugin { static let ERROR_GEOFENCE_LIMIT_EXCEEDED = "GEOFENCE_LIMIT_EXCEEDED" static let ERROR_GEOFENCE_NOT_AVAILABLE = "GEOFENCE_NOT_AVAILABLE" static let ERROR_LOCATION_SERVICES_DISABLED = "LOCATION_SERVICES_DISABLED" static let ERROR_PERMISSION_DENIED = "PERMISSION_DENIED" static let ERROR_UNKNOWN = "UNKNOWN" lazy var geoNotificationManager = GeoNotificationManager() let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT override func pluginInitialize () { NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(GeofencePlugin.didReceiveLocalNotification(_:)), name: "CDVLocalNotification", object: nil ) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(GeofencePlugin.didReceiveTransition(_:)), name: "handleTransition", object: nil ) } func initialize(command: CDVInvokedUrlCommand) { log("Plugin initialization") if iOS8 { promptForNotificationPermission() } geoNotificationManager = GeoNotificationManager() geoNotificationManager.registerPermissions() let (ok, warnings, errors) = checkRequirements() log(warnings) log(errors) let result: CDVPluginResult if ok { result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: warnings.joinWithSeparator("\n")) } else { result = CDVPluginResult( status: CDVCommandStatus_ERROR, messageAsDictionary: errors.first ) } commandDelegate!.sendPluginResult(result, callbackId: command.callbackId) } func deviceReady(command: CDVInvokedUrlCommand) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } func ping(command: CDVInvokedUrlCommand) { log("Ping") let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } func promptForNotificationPermission() { UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings( forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge], categories: nil ) ) } func addOrUpdate(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { let geo = command.arguments[0] self.geoNotificationManager.addOrUpdateGeoNotification(JSON(geo), completion: { (errors: [[String:String]]?) -> Void in dispatch_async(dispatch_get_main_queue()) { var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) if (errors != nil) { pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR, messageAsDictionary: errors!.first ) } self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } }) } } func getWatched(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { let watched = self.geoNotificationManager.getWatchedGeoNotifications()! let watchedJsonString = watched.description dispatch_async(dispatch_get_main_queue()) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: watchedJsonString) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func remove(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { for id in command.arguments { self.geoNotificationManager.removeGeoNotification(id as! String) } dispatch_async(dispatch_get_main_queue()) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func removeAll(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { self.geoNotificationManager.removeAllGeoNotifications() dispatch_async(dispatch_get_main_queue()) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func didReceiveTransition (notification: NSNotification) { log("didReceiveTransition") if let geoNotificationString = notification.object as? String { let js = "setTimeout('geofence.onTransitionReceived([" + geoNotificationString + "])',0)" evaluateJs(js) } } func didReceiveLocalNotification (notification: NSNotification) { log("didReceiveLocalNotification") if UIApplication.sharedApplication().applicationState != UIApplicationState.Active { var data = "undefined" if let uiNotification = notification.object as? UILocalNotification { if let notificationData = uiNotification.userInfo?["geofence.notification.data"] as? String { data = notificationData } let js = "setTimeout('geofence.onNotificationClicked(" + data + ")',0)" evaluateJs(js) } } } func evaluateJs (script: String) { if let webView = webView { if let uiWebView = webView as? UIWebView { uiWebView.stringByEvaluatingJavaScriptFromString(script) } else if let wkWebView = webView as? WKWebView { wkWebView.evaluateJavaScript(script, completionHandler: nil) } } else { log("webView is nil") } } } struct Command { var geoNotification: JSON var callback: Callback } @available(iOS 8.0, *) class GeoNotificationManager : NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager() let store = GeoNotificationStore() var addOrUpdateCallbacks = [CLCircularRegion:Command]() override init() { log("GeoNotificationManager init") super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest } func registerPermissions() { if iOS8 { locationManager.requestAlwaysAuthorization() } } func addOrUpdateGeoNotification(geoNotification: JSON, completion: Callback) { log("GeoNotificationManager addOrUpdate") let (ok, warnings, errors) = checkRequirements() log(warnings) log(errors) if (!ok) { return completion(errors) } let location = CLLocationCoordinate2DMake( geoNotification["latitude"].doubleValue, geoNotification["longitude"].doubleValue ) log("AddOrUpdate geo: \(geoNotification)") let radius = geoNotification["radius"].doubleValue as CLLocationDistance let id = geoNotification["id"].stringValue let region = CLCircularRegion(center: location, radius: radius, identifier: id) var transitionType = 0 if let i = geoNotification["transitionType"].int { transitionType = i } region.notifyOnEntry = 0 != transitionType & 1 region.notifyOnExit = 0 != transitionType & 2 let command = Command(geoNotification: geoNotification, callback: completion) addOrUpdateCallbacks[region] = command locationManager.startMonitoringForRegion(region) } func getWatchedGeoNotifications() -> [JSON]? { return store.getAll() } func getMonitoredRegion(id: String) -> CLRegion? { for object in locationManager.monitoredRegions { let region = object if (region.identifier == id) { return region } } return nil } func removeGeoNotification(id: String) { store.remove(id) let region = getMonitoredRegion(id) if (region != nil) { log("Stop monitoring region \(id)") locationManager.stopMonitoringForRegion(region!) } } func removeAllGeoNotifications() { store.clear() for object in locationManager.monitoredRegions { let region = object log("Stop monitoring region \(region.identifier)") locationManager.stopMonitoringForRegion(region) } } func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) { log("Entering region \(region.identifier)") handleTransition(region, transitionType: 1) } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { log("Exiting region \(region.identifier)") handleTransition(region, transitionType: 2) } func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion) { if let clRegion = region as? CLCircularRegion { if let command = self.addOrUpdateCallbacks[clRegion] { store.addOrUpdate(command.geoNotification) log("Starting monitoring for region \(region.identifier)") command.callback(nil) self.addOrUpdateCallbacks.removeValueForKey(clRegion) } } } func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) { log("Monitoring region \(region!.identifier) failed. Reson: \(error.description)") if let clRegion = region as? CLCircularRegion { if let command = self.addOrUpdateCallbacks[clRegion] { var errors = [[String:String]]() if locationManager.monitoredRegions.count >= 20 { errors.append([ "code": GeofencePlugin.ERROR_GEOFENCE_LIMIT_EXCEEDED, "message": error.description ]) } else { errors.append([ "code": GeofencePlugin.ERROR_UNKNOWN, "message": error.description ]) } command.callback(errors) self.addOrUpdateCallbacks.removeValueForKey(clRegion) } } } func handleTransition(region: CLRegion!, transitionType: Int) { if var geoNotification = store.findById(region.identifier) { geoNotification["transitionType"].int = transitionType if geoNotification["notification"].isExists() { sendTransitionToServer(geoNotification) notifyAbout(geoNotification) } NSNotificationCenter.defaultCenter().postNotificationName("handleTransition", object: geoNotification.rawString(NSUTF8StringEncoding, options: [])) } } func sendTransitionToServer(_ geo: JSON) { log("Sending transition info to server") let urlString = geo["serverURL"].string let url = URL(string: urlString!)! let session = URLSession.shared var request = URLRequest(url: url) do { request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let jsonData: [String : JSON] = geo["notification"]["data"].dictionary! var postData:[String : String] = [:] jsonData.forEach { (k, v) in postData[k] = v.rawString() } request.httpBody = try? JSONSerialization.data(withJSONObject: postData) let task = session.dataTask(with: request, completionHandler: { (_, response, error) -> Void in print("Response from server: \(response), errors: \(error)") }) task.resume() } catch { print("error") } } func notifyAbout(geo: JSON) { log("Creating notification") let notification = UILocalNotification() notification.timeZone = NSTimeZone.defaultTimeZone() let dateTime = NSDate() notification.fireDate = dateTime notification.soundName = UILocalNotificationDefaultSoundName notification.alertBody = geo["notification"]["text"].stringValue if let json = geo["notification"]["data"] as JSON? { notification.userInfo = ["geofence.notification.data": json.rawString(NSUTF8StringEncoding, options: [])!] } UIApplication.sharedApplication().scheduleLocalNotification(notification) if let vibrate = geo["notification"]["vibrate"].array { if (!vibrate.isEmpty && vibrate[0].intValue > 0) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } } } } // TODO: pass errors to cordova application class GeoNotificationStore { init() { createDBStructure() } func createDBStructure() { let (tables, err) = SD.existingTables() if (err != nil) { log("Cannot fetch sqlite tables: \(err)") return } if (tables.filter { $0 == "GeoNotifications" }.count == 0) { if let err = SD.executeChange("CREATE TABLE GeoNotifications (ID TEXT PRIMARY KEY, Data TEXT)") { //there was an error during this function, handle it here log("Error while creating GeoNotifications table: \(err)") } else { //no error, the table was created successfully log("GeoNotifications table was created successfully") } } } func addOrUpdate(geoNotification: JSON) { if (findById(geoNotification["id"].stringValue) != nil) { update(geoNotification) } else { add(geoNotification) } } func add(geoNotification: JSON) { let id = geoNotification["id"].stringValue let err = SD.executeChange("INSERT INTO GeoNotifications (Id, Data) VALUES(?, ?)", withArgs: [id, geoNotification.description]) if err != nil { log("Error while adding \(id) GeoNotification: \(err)") } } func update(geoNotification: JSON) { let id = geoNotification["id"].stringValue let err = SD.executeChange("UPDATE GeoNotifications SET Data = ? WHERE Id = ?", withArgs: [geoNotification.description, id]) if err != nil { log("Error while adding \(id) GeoNotification: \(err)") } } func findById(id: String) -> JSON? { let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications WHERE Id = ?", withArgs: [id]) if err != nil { //there was an error during the query, handle it here log("Error while fetching \(id) GeoNotification table: \(err)") return nil } else { if (resultSet.count > 0) { let jsonString = resultSet[0]["Data"]!.asString()! return JSON(data: jsonString.dataUsingEncoding(NSUTF8StringEncoding)!) } else { return nil } } } func getAll() -> [JSON]? { let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications") if err != nil { //there was an error during the query, handle it here log("Error while fetching from GeoNotifications table: \(err)") return nil } else { var results = [JSON]() for row in resultSet { if let data = row["Data"]?.asString() { results.append(JSON(data: data.dataUsingEncoding(NSUTF8StringEncoding)!)) } } return results } } func remove(id: String) { let err = SD.executeChange("DELETE FROM GeoNotifications WHERE Id = ?", withArgs: [id]) if err != nil { log("Error while removing \(id) GeoNotification: \(err)") } } func clear() { let err = SD.executeChange("DELETE FROM GeoNotifications") if err != nil { log("Error while deleting all from GeoNotifications: \(err)") } } }
apache-2.0
f5b0c0fc842f6172ab3712802d8f0502
34.106007
159
0.599547
5.262182
false
false
false
false
nslogo/DouYuZB
DouYuZB/DouYuZB/Classes/Main/View/PageContentView.swift
1
5775
// // PageContentView.swift // DouYuZB // // Created by nie on 16/9/20. // Copyright © 2016年 ZoroNie. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } fileprivate let contentCellID = "contentCellID" class PageContentView: UIView { //MARK : - 定义属性 fileprivate var childVCs : [UIViewController] fileprivate weak var parentViewController : UIViewController?//使用weak修饰避免和父控制器形成互相引用,而且使用weak修饰的话是可选类型,需要在类型后面加? fileprivate var startOffsetX : CGFloat = 0 fileprivate var isForbidScrollDelegate : Bool = false weak var delegate : PageContentViewDelegate? //MARK : - 懒加载属性 fileprivate lazy var collectionView : UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionFrame : CGRect = CGRect(x: 0, y: 0, width: 0, height: 0) let collectionView = UICollectionView(frame: collectionFrame, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.scrollsToTop = false collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID) return collectionView }() init(frame: CGRect, childVCs : [UIViewController], parentViewController : UIViewController ) { //将传进来的两个值保存到这个文件里 self.childVCs = childVCs self.parentViewController = parentViewController super.init(frame: frame) //设置UI界面 setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置UI界面 extension PageContentView { //将获取到的子控制器数组中的子控制器全部添加到父控制器中 fileprivate func setUpUI() { for childVC in childVCs { parentViewController?.addChildViewController(childVC) } addSubview(collectionView) collectionView.frame = bounds } } // MARK: - UICollectionViewDataSource extension PageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVCs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVC = childVCs[indexPath.item] childVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVC.view) return cell } } // MARK:- 遵守UICollectionViewDelegate extension PageContentView : UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 0.判断是否是点击事件 if isForbidScrollDelegate { return } // 1.定义获取需要的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 // 1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVCs.count { targetIndex = childVCs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { // 右滑 // 1.计算progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) // 2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) // 3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVCs.count { sourceIndex = childVCs.count - 1 } } // 3.将progress/sourceIndex/targetIndex传递给titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } // MARK: - 对外暴露的方法 extension PageContentView { public func setCurrentIndex(currentIndex : Int) { let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x : offsetX, y : 0), animated: false) } }
mit
828f6f8e5cd31651de7100891972be36
30.287356
124
0.640522
5.694561
false
false
false
false
keyfun/hk-chinese-words-ios-library
HKChineseWords/Classes/HKChineseWords.swift
1
5983
// // HKChineseWords.swift // HKChineseWords // // Created by Key Hui on 01/20/2017. // Copyright (c) 2017 Key Hui. All rights reserved. // import Foundation public class HKChineseWords { private let POST_URL = "https://www.edbchinese.hk/lexlist_ch/result.jsp" private let PATTERN = "swf?cidx=" private let GIF_URL = "https://www.edbchinese.hk/EmbziciwebRes/stkdemo/%@/%@.gif" // eg: https://www.edbchinese.hk/EmbziciwebRes/stkdemo/3001-4000/3894.gif // POST Parameters: // searchMethod = direct // searchCriteria = 字 // sortBy = storke // jpC = Ishk // Submit = 搜尋 public static let sharedInstance = HKChineseWords() private init() { } public func getInfo() -> String { return POST_URL } public func getImages(_ text: String, completion: @escaping (_ images: Array<UIImage>, _ error: Error?) -> Void) { self.getUrl(text) { (url: String, error: Error?) in if let checkedUrl = URL(string: url) { self.downloadImage(url: checkedUrl, completion: completion) } else { completion([], error) } } } public func getUrl(_ text: String, completion: @escaping (_ url: String, _ error: Error?) -> Void) { var request = URLRequest(url: URL(string: POST_URL)!) request.httpMethod = "POST" let postString = "searchMethod=direct&sortBy=storke&jpC=Ishk&searchCriteria=" + text request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } let responseString = String(data: data, encoding: .utf8) // print("responseString = \(responseString)") if responseString != nil { let id: Int = self.getWordId(responseString!) if id != -1 { print("word id = \(id)") let url: String = self.getImageUrl(id) print("gif url = \(url)") completion(url, nil) } else { print("Invalid id") completion("", NSError(domain: "keyfun.app.HKChineseWords", code: 405, userInfo: nil)) } } else { print("Invalid responseString") } } task.resume() } private func getWordId(_ text: String) -> Int { if let range = text.range(of: PATTERN) { let lo = text.index(range.lowerBound, offsetBy: PATTERN.count) let hi = text.index(range.lowerBound, offsetBy: PATTERN.count + 4) let subRange = lo ..< hi let id: String = String(text[subRange]) // print("find id = \(id)") if let idInt: Int = Int(id) { return idInt } } return -1 } private func getImageUrl(_ id: Int) -> String { let lower: Int = Int(floor(Double(id / 1000))) let upper: Int = (lower + 1) * 1000 var idStr: String = String(id) var lowerStr: String = "" var upperStr: String = "" if id < 1000 { // append leading zero lowerStr = String(format: "%04d", lower + 1) idStr = String(format: "%04d", id) } else { lowerStr = String(lower * 1000 + 1) } if id > 4000 { upperStr = "ZC" } else { upperStr = String(upper) } let subPath: String = lowerStr + "-" + upperStr let url: String = String(format: GIF_URL, subPath, idStr) return url } private func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) { URLSession.shared.dataTask(with: url) { (data, response, error) in completion(data, response, error) }.resume() } private func downloadImage(url: URL, completion: @escaping (_ images: Array<UIImage>, _ error: Error?) -> Void) { print("Download Started") getDataFromUrl(url: url) { (data, response, error) in guard let data = data, error == nil else { return } print(response?.suggestedFilename ?? url.lastPathComponent) print("Download Finished") DispatchQueue.main.async() { () -> Void in if let image = UIImage(data: data) { // return image data self.convertImageArr(image, completion: completion) } else { // print("Download Failed") completion([], NSError(domain: "keyfun.app.HKChineseWords", code: 404, userInfo: nil)) } } } } private func convertImageArr(_ rawImage: UIImage, completion: @escaping (_ images: Array<UIImage>, _ error: Error?) -> Void) { var imageArr = Array<UIImage>() let width = Int(rawImage.size.width) let height = Int(rawImage.size.height) let numOfFrame = Int(width / height) for i: Int in 0 ..< numOfFrame { let x = i * height let cropRect = CGRect(x: x, y: 0, width: height, height: height) let imageRef = rawImage.cgImage!.cropping(to: cropRect) let cropImage = UIImage(cgImage: imageRef!) imageArr.append(cropImage) } // return imageArr completion(imageArr, nil) } }
mit
2fb73f3dad3cbba8ddfbd8baf2c1bdb3
34.790419
133
0.542747
4.281519
false
false
false
false
zhuyunfeng1224/XHGuideViewController
XHGuideViewController/XHGuideViewController.swift
1
5890
// // XHGuideViewController.swift // XHGuideViewController // // Created by echo on 16/7/26. // Copyright © 2016年 羲和. All rights reserved. // import Foundation import UIKit open class XHGuideViewController: UIViewController, UIScrollViewDelegate { let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height let timeLabelWidth: CGFloat = 30.0 let timeLabelHeight: CGFloat = 20.0 let timeLabelY: CGFloat = 20.0 let skipButtonWidth: CGFloat = 50.0 let skipButtonHeight: CGFloat = 30.0 let pageControlWidth: CGFloat = 100 let pageControlHeight: CGFloat = 30 let pageControlY: CGFloat = UIScreen.main.bounds.height - 100 open var viewControllers: [UIViewController] = [] open var autoClose: Bool = true open var showSkipButton: Bool = true open var showTime: Int = 5 open var actionSkip: (()->())! = {} // MARK:lazy load // scrollView fileprivate lazy var scrollView: UIScrollView = { var newValue: UIScrollView = UIScrollView(frame: self.view.bounds) newValue.isPagingEnabled = true newValue.backgroundColor = UIColor.clear newValue.alwaysBounceHorizontal = true newValue.delegate = self return newValue }() // pageControl open lazy var pageControl: UIPageControl = { var newValue: UIPageControl = UIPageControl(frame: CGRect(x: (self.screenWidth - self.pageControlWidth)/2, y: self.pageControlY, width: self.pageControlWidth, height: self.pageControlHeight)) newValue.hidesForSinglePage = true newValue.addTarget(self, action: #selector(pageControlValueChanged(_:)), for: .valueChanged) return newValue }() // timeToCloseLabel open lazy var timeToCloseLabel: UILabel = { var newValue: UILabel = UILabel(frame: CGRect(x: self.screenWidth - self.timeLabelWidth - self.skipButtonWidth - 20, y: self.timeLabelY, width: self.timeLabelWidth, height: self.timeLabelHeight)) newValue.font = UIFont.systemFont(ofSize: 12) newValue.textColor = UIColor.darkGray return newValue }() // skipButton open lazy var skipButton: UIButton = { var newValue: UIButton = UIButton(frame: CGRect(x: self.timeToCloseLabel.frame.maxX, y: self.timeToCloseLabel.frame.minY, width: self.skipButtonWidth, height: self.skipButtonHeight)) newValue.setTitle("跳过", for: UIControlState()) newValue.setTitleColor(UIColor.darkGray, for: UIControlState()) newValue.titleLabel?.font = UIFont.systemFont(ofSize: 12) newValue.backgroundColor = UIColor.black.withAlphaComponent(0.2) newValue.layer.cornerRadius = 5 newValue.layer.masksToBounds = true newValue .addTarget(self, action: #selector(skipButtonClicked(_:)), for: .touchUpInside) return newValue }() // backgroundImage open var backgroundImageView: UIImageView = UIImageView() // MARK: Initialize override open func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.loadSubViews() self.timeToCloseLabel.isHidden = !self.autoClose } override open func viewDidAppear(_ animated: Bool) { if self.autoClose == true { let timer: Timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(XHGuideViewController.delayTimeChanged), userInfo: nil, repeats: true) timer.fire() } } fileprivate func loadSubViews() { self.backgroundImageView.frame = self.view.bounds self.view.addSubview(self.backgroundImageView) self.scrollView.contentSize = CGSize(width: scrollView.frame.width * CGFloat(self.viewControllers.count), height: scrollView.frame.height) for i in 0 ..< self.viewControllers.count { let vc: XHGuideContentViewController = self.viewControllers[i] as! XHGuideContentViewController vc.index = i let view = vc.view view?.frame = CGRect(x: CGFloat(i) * scrollView.frame.width, y: 0, width: scrollView.frame.width, height: scrollView.frame.height) self.scrollView.addSubview(view!) } self.view.addSubview(self.scrollView) self.pageControl.numberOfPages = self.viewControllers.count self.view.addSubview(self.pageControl) self.view.addSubview(self.timeToCloseLabel) if self.showSkipButton == true { self.view.addSubview(self.skipButton) } } // MARK: UIScrollViewDelegate open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let offsetX: CGFloat = scrollView.contentOffset.x if (self.scrollView.contentSize.width - offsetX) < CGFloat(self.scrollView.frame.width - 60) { self.actionSkip() } } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let page: NSInteger = Int(scrollView.contentOffset.x/scrollView.frame.width) self.pageControl.currentPage = page } // MARK: Actions @objc fileprivate func pageControlValueChanged(_ sender: UIPageControl) { let page = sender.currentPage self.scrollView.contentOffset = CGPoint(x: CGFloat(page) * self.scrollView.frame.width, y: self.scrollView.contentOffset.y) } @objc fileprivate func skipButtonClicked(_ sender: UIButton) { self.actionSkip() } @objc fileprivate func delayTimeChanged(_ timer: Timer) { self.timeToCloseLabel.text = "\(self.showTime<0 ? 0: self.showTime)s" if self.showTime <= 0 { timer.invalidate() self.actionSkip() } self.showTime -= 1 } }
mit
b251d8d9aebdd2da0a5b0eb5833004f5
37.424837
203
0.664059
4.737309
false
false
false
false
sean915213/SGYWebSession
SGYWebSession/Classes/WebRequest.swift
1
3906
// // WebRequest.swift // // Created by Sean Young on 11/13/15. // Copyright © 2015 Sean G Young. All rights reserved. // import Foundation //public class WebRequest2 { // // // MARK: - Initialization // // public convenience init(method: HTTPVerb, fullUrl: URL, completed: (result: WebResult<T, U>) -> Void) { // self.init(method: method, fullUrl: fullUrl) // completedCallback = completed // } // // public init(method: HTTPVerb, fullUrl: URL) { // self.method = method // self.url = fullUrl // } // // // MARK: - Properties // // public let method: HTTPVerb // public let url: URL // // public var additionalHeaders: [String: String]? // public var requestObject: SerializableObject? // // public var completedCallback: ((result: WebResult<T, U>) -> Void)? // // public var displayNetworkActivity = false // // // MARK: - Methods // // public func setCompletedCallback(_ callback: ((result: WebResult<T, U>) -> Void)?) { // completedCallback = callback // } //} public struct WebRequestID: Equatable { init(_ id: String) { identifier = id } let identifier: String } public func ==(lhs: WebRequestID, rhs: WebRequestID) -> Bool { return lhs.identifier == rhs.identifier } open class WebRequest { // public typealias WebRequestCallback = (WebResult<T, U>) -> Void // MARK: - Initialization // public convenience init(method: HTTPVerb, fullUrl: URL, completed: WebRequestCallback) { // self.init(method: method, fullUrl: fullUrl) // completedCallback = completed // } public init(method: HTTPVerb, fullUrl: URL) { self.method = method self.url = fullUrl } // MARK: - Properties // The unique id of this request public lazy var requestID = WebRequestID(UUID.init().uuidString) // Request verb public let method: HTTPVerb // Full url public let url: URL // Additional headers to add to default public var additionalHeaders: [String: String]? // The object to serialize as body public var requestObject: SerializableObject? // Whether this request should activate the network activity indicator public var displayNetworkActivity = false // // The request's callback // public var completedCallback: WebRequestCallback? // // // MARK: - Methods // // public func setCompletedCallback(_ callback: ((_ result: WebResult<T, U>) -> Void)?) { // completedCallback = callback // } } /** open class WebRequest<T: DeserializableObject, U: DeserializableObject> { public typealias WebRequestCallback = (WebResult<T, U>) -> Void // MARK: - Initialization public convenience init(method: HTTPVerb, fullUrl: URL, completed: WebRequestCallback) { self.init(method: method, fullUrl: fullUrl) completedCallback = completed } public init(method: HTTPVerb, fullUrl: URL) { self.method = method self.url = fullUrl } // MARK: - Properties // The unique id of this request public lazy var requestID = WebRequestID(UUID.init().uuidString) // Request verb public let method: HTTPVerb // Full url public let url: URL // Additional headers to add to default public var additionalHeaders: [String: String]? // The object to serialize as body public var requestObject: SerializableObject? // Whether this request should activate the network activity indicator public var displayNetworkActivity = false // The request's callback public var completedCallback: WebRequestCallback? // MARK: - Methods public func setCompletedCallback(_ callback: ((_ result: WebResult<T, U>) -> Void)?) { completedCallback = callback } } **/
mit
6aca2368f1e95fb316d779d33caf973d
26.695035
109
0.63201
4.2631
false
false
false
false
MiniDOM/MiniDOM
Tests/MiniDOMTests/ParserPlistTests.swift
1
4496
// // ParserPlistTests.swift // MiniDOM // // Copyright 2017-2020 Anodized Software, Inc. // // 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 MiniDOM import XCTest class ParserPlistTests: XCTestCase { var source: String! var document: Document! override func setUp() { super.setUp() source = [ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">", "<plist version=\"1.0\">", "<dict>", "<key>CFBundleDevelopmentRegion</key>", "<string>en</string>", "<key>CFBundleExecutable</key>", "<string>$(EXECUTABLE_NAME)</string>", "<key>CFBundleIdentifier</key>", "<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>", "<key>CFBundleInfoDictionaryVersion</key>", "<string>6.0</string>", "<key>CFBundleName</key>", "<string>$(PRODUCT_NAME)</string>", "<key>CFBundlePackageType</key>", "<string>BNDL</string>", "<key>CFBundleShortVersionString</key>", "<string>1.0</string>", "<key>CFBundleVersion</key>", "<string>1</string>", "</dict>", "</plist>", ].joined(separator: "\n") document = loadXML(string: source) } func testRootElement() { let documentElement = document.documentElement XCTAssertNotNil(documentElement) XCTAssertEqual(documentElement?.nodeName, "plist") XCTAssertEqual(documentElement?.attributes ?? [:], [ "version": "1.0" ]) } func testSingleDictElementUnderRoot() { let documentElement = document.documentElement XCTAssertEqual(documentElement?.childElements.count, 1) let dict = documentElement?.firstChildElement XCTAssertNotNil(dict) XCTAssertEqual(dict?.nodeName, "dict") XCTAssertEqual(dict?.childElements.count, 16) } func testDictElementIsCorrect() { let expectedElementNames: [String] = [ "key", "string", "key", "string", "key", "string", "key", "string", "key", "string", "key", "string", "key", "string", "key", "string", ] let dict = document.documentElement?.firstChildElement let actualElementNames: [String] = dict?.childElements.map { $0.nodeName } ?? [] XCTAssertEqual(expectedElementNames, actualElementNames) let expectedNodeValues: [String] = [ "CFBundleDevelopmentRegion", "en", "CFBundleExecutable", "$(EXECUTABLE_NAME)", "CFBundleIdentifier", "$(PRODUCT_BUNDLE_IDENTIFIER)", "CFBundleInfoDictionaryVersion", "6.0", "CFBundleName", "$(PRODUCT_NAME)", "CFBundlePackageType", "BNDL", "CFBundleShortVersionString", "1.0", "CFBundleVersion", "1", ] let actualNodeValues: [String] = dict?.children.compactMap { $0.firstChild?.nodeValue } ?? [] XCTAssertEqual(expectedNodeValues, actualNodeValues) } }
mit
af8412791bcff199609762a3b7b89174
32.804511
121
0.586077
4.67846
false
true
false
false
mssun/passforios
passKit/Protocols/AlertPresenting.swift
2
1833
// // AlertPresenting.swift // pass // // Copyright © 2022 Bob Sun. All rights reserved. // import UIKit public typealias AlertAction = (UIAlertAction) -> Void public protocol AlertPresenting { func presentAlert(title: String, message: String) func presentFailureAlert(title: String?, message: String, action: AlertAction?) func presentAlertWithAction(title: String, message: String, action: AlertAction?) } public extension AlertPresenting where Self: UIViewController { func presentAlert(title: String, message: String) { presentAlert( title: title, message: message, actions: [UIAlertAction(title: "OK", style: .cancel, handler: nil)] ) } // swiftlint:disable function_default_parameter_at_end func presentFailureAlert(title: String? = nil, message: String, action: AlertAction? = nil) { let title = title ?? "Error" presentAlert( title: title, message: message, actions: [UIAlertAction(title: "OK", style: .cancel, handler: action)] ) } func presentAlertWithAction(title: String, message: String, action: AlertAction?) { presentAlert( title: title, message: message, actions: [ UIAlertAction(title: "Yes", style: .default, handler: action), UIAlertAction(title: "No", style: .cancel, handler: nil), ] ) } private func presentAlert(title: String, message: String, actions: [UIAlertAction] = []) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) actions.forEach { action in alertController.addAction(action) } present(alertController, animated: true, completion: nil) } }
mit
a38142eef8b3a8e48916bf0a4d61c8e9
32.309091
103
0.629913
4.637975
false
false
false
false
64characters/Telephone
TelephoneTests/CallHistoryViewEventTargetTests.swift
1
9387
// // CallHistoryViewEventTargetTests.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UseCases import UseCasesTestDoubles import XCTest final class CallHistoryViewEventTargetTests: XCTestCase { // MARK: - Should reload data func testExecutesCallHistoryRecordGetAllUseCaseOnShouldReloadData() { let get = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: get, purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.shouldReloadData() XCTAssertTrue(get.didCallExecute) } func testExecutesPurchaseCheckUseCaseOnShouldReloadData() { let purchaseCheck = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: purchaseCheck, recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.shouldReloadData() XCTAssertTrue(purchaseCheck.didCallExecute) } // MARK: - Did update history func testExecutesCallHistoryRecordGetAllUseCaseOnDidUpdateHistory() { let get = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: get, purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.didUpdate(TruncatingCallHistory()) XCTAssertTrue(get.didCallExecute) } func testExecutesPurchaseCheckUseCaseOnDidUpdateHistory() { let purchaseCheck = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: purchaseCheck, recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.didUpdate(TruncatingCallHistory()) XCTAssertTrue(purchaseCheck.didCallExecute) } // MARK: - Did purchase func testExecutesCallHistoryRecordGetAllUseCaseOnDidPurchase() { let get = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: get, purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.didPurchase() XCTAssertTrue(get.didCallExecute) } func testExecutesPurchaseCheckUseCaseOnDidPurchase() { let purchaseCheck = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: purchaseCheck, recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.didPurchase() XCTAssertTrue(purchaseCheck.didCallExecute) } // MARK: - Did restore purchases func testExecutesCallHistoryRecordGetAllUseCaseOnDidRestorePurchases() { let get = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: get, purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.didRestorePurchases() XCTAssertTrue(get.didCallExecute) } func testExecutesPurchaseCheckUseCaseOnDidRestorePurchases() { let purchaseCheck = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: purchaseCheck, recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.didRestorePurchases() XCTAssertTrue(purchaseCheck.didCallExecute) } // MARK: - Day did change func testExecutesCallHistoryRecordGetAllUseCaseOnDayDidChange() { let get = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: get, purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.dayDidChange() XCTAssertTrue(get.didCallExecute) } func testExecutesPurchaseCheckUseCaseOnDayDidChange() { let purchaseCheck = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: purchaseCheck, recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.dayDidChange() XCTAssertTrue(purchaseCheck.didCallExecute) } // MARK: - Should remove all records func testExecutesCallHistoryRecordRemoveAllUseCaseOnShouldRemoveAllRecords() { let remove = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: UseCaseSpy(), recordRemoveAll: remove, recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.shouldRemoveAllRecords() XCTAssertTrue(remove.didCallExecute) } // MARK: - Did pick record func testCreatesCallHistoryCallMakeUseCaseWithExpectedIdentifierOnDidPickRecord() { let factory = CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: factory ) let identifier = "any" sut.didPickRecord(withIdentifier: identifier) XCTAssertEqual(factory.invokedIdentifier, identifier) } func testExecutesCallHistoryCallMakeUseCaseOnDidPickRecord() { let callMake = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: callMake) ) sut.didPickRecord(withIdentifier: "any") XCTAssertTrue(callMake.didCallExecute) } // MARK: - Should remove record func testCreatesCallHistoryRecordRemoveUseCaseWithExpectedIdentifierOnShouldRemoveRecord() { let factory = CallHistoryRecordRemoveUseCaseFactorySpy(remove: UseCaseSpy()) let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: factory, callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) let identifier = "any" sut.shouldRemoveRecord(withIdentifier: identifier) XCTAssertEqual(factory.invokedIdentifier, identifier) } func testExecutesCallHistoryRecordRemoveUseCaseOnShouldRemoveRecord() { let remove = UseCaseSpy() let sut = CallHistoryViewEventTarget( recordsGet: UseCaseSpy(), purchaseCheck: UseCaseSpy(), recordRemoveAll: UseCaseSpy(), recordRemove: CallHistoryRecordRemoveUseCaseFactorySpy(remove: remove), callMake: CallHistoryCallMakeUseCaseFactorySpy(callMake: UseCaseSpy()) ) sut.shouldRemoveRecord(withIdentifier: "any") XCTAssertTrue(remove.didCallExecute) } }
gpl-3.0
f2fb427b1c9d6eb4e1772e140d83d5e8
34.149813
96
0.679169
5.344533
false
true
false
false
materik/stubborn
Stubborn/Stub/Stub.swift
1
2903
import QueryString extension Stubborn { public class Stub { private var numberOfRequests: Int = 0 var index: Int? public private(set) var url: Request.URL public var queryString: QueryString? public var body: Body.Dictionary? public var delay: Delay? var response: RequestResponse init(_ url: String, response: @escaping RequestResponse) { self.url = url self.response = response } convenience init(_ url: String, dictionary: Body.Dictionary) { self.init(url) { _ in dictionary } } convenience init(_ url: String, error: Body.Error) { self.init(url) { _ in error } } convenience init(_ url: String, simple: Body.Simple) { self.init(url) { _ in simple } } convenience init(_ url: String, resource: Body.Resource) { self.init(url) { _ in resource } } func loadBody(_ request: Request) -> Body { self.numberOfRequests += 1 var request = request request.numberOfRequests = self.numberOfRequests return self.response(request) } func isStubbing(request: Request) -> Bool { guard request.url =~ self.url else { return false } if let queryString = self.queryString, queryString != request.queryString { return false } if let body = self.body, !(request.body?.contains(body) ?? false) { return false } return true } } } extension Stubborn.Stub: CustomStringConvertible { public var description: String { var description = "Stub({" description = "\(description)\n Index: \(self.index ?? -1)" description = "\(description)\n Url: \(self.url)" description = "\(description)\n QueryString: \(self.queryString ?? QueryString())" description = "\(description)\n Body: \(self.body ?? Stubborn.Body.Dictionary())" description = "\(description)\n Delay: \(String(self.delay?.rawValue ?? 0))" description = "\(description)\n})" return description } } infix operator ⏱ infix operator ❓ infix operator ❗️ @discardableResult public func ⏱ (delay: Stubborn.Delay?, stub: Stubborn.Stub) -> Stubborn.Stub { stub.delay = delay return stub } @discardableResult public func ❓ (queryString: QueryString?, stub: Stubborn.Stub) -> Stubborn.Stub { stub.queryString = queryString return stub } @discardableResult public func ❗️ (body: Stubborn.Body.Dictionary?, stub: Stubborn.Stub) -> Stubborn.Stub { stub.body = body return stub }
mit
dc15eae8ecb907035695c7fa362ad5aa
27.87
93
0.558365
4.626603
false
false
false
false
bitjammer/swift
test/SILGen/guaranteed_closure_context.swift
1
3164
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-guaranteed-closure-contexts %s | %FileCheck %s func use<T>(_: T) {} func escape(_ f: () -> ()) {} protocol P {} class C: P {} struct S {} // CHECK-LABEL: sil hidden @_T026guaranteed_closure_context0A9_capturesyyF func guaranteed_captures() { // CHECK: [[MUTABLE_TRIVIAL_BOX:%.*]] = alloc_box ${ var S } var mutableTrivial = S() // CHECK: [[MUTABLE_RETAINABLE_BOX:%.*]] = alloc_box ${ var C } var mutableRetainable = C() // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX:%.*]] = alloc_box ${ var P } var mutableAddressOnly: P = C() // CHECK: [[IMMUTABLE_TRIVIAL:%.*]] = apply {{.*}} -> S let immutableTrivial = S() // CHECK: [[IMMUTABLE_RETAINABLE:%.*]] = apply {{.*}} -> @owned C let immutableRetainable = C() // CHECK: [[IMMUTABLE_ADDRESS_ONLY:%.*]] = alloc_stack $P let immutableAddressOnly: P = C() func captureEverything() { use((mutableTrivial, mutableRetainable, mutableAddressOnly, immutableTrivial, immutableRetainable, immutableAddressOnly)) } // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[FN:%.*]] = function_ref [[FN_NAME:@_T026guaranteed_closure_context0A9_capturesyyF17captureEverythingL_yyF]] // CHECK: apply [[FN]]([[MUTABLE_TRIVIAL_BOX]], [[MUTABLE_RETAINABLE_BOX]], [[MUTABLE_ADDRESS_ONLY_BOX]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE]], [[IMMUTABLE_AO_BOX]]) captureEverything() // CHECK: destroy_value [[IMMUTABLE_AO_BOX]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // -- partial_apply still takes ownership of its arguments. // CHECK: [[FN:%.*]] = function_ref [[FN_NAME]] // CHECK: [[MUTABLE_TRIVIAL_BOX_COPY:%.*]] = copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK: [[MUTABLE_RETAINABLE_BOX_COPY:%.*]] = copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX_COPY:%.*]] = copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK: [[IMMUTABLE_RETAINABLE_COPY:%.*]] = copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[CLOSURE:%.*]] = partial_apply {{.*}}([[MUTABLE_TRIVIAL_BOX_COPY]], [[MUTABLE_RETAINABLE_BOX_COPY]], [[MUTABLE_ADDRESS_ONLY_BOX_COPY]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE_COPY]], [[IMMUTABLE_AO_BOX]]) // CHECK: apply {{.*}}[[CLOSURE]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK-NOT: destroy_value [[IMMUTABLE_AO_BOX]] escape(captureEverything) } // CHECK: sil shared [[FN_NAME]] : $@convention(thin) (@guaranteed { var S }, @guaranteed { var C }, @guaranteed { var P }, S, @guaranteed C, @guaranteed { var P })
apache-2.0
553a1d12aeac6c4bd617bff574c8b7d4
44.855072
224
0.647914
3.575141
false
false
false
false
darren90/Gankoo_Swift
Gankoo/Gankoo/Classes/Home/HomeViewController.swift
1
5065
// // HomeViewController.swift // Gankoo // // Created by Fengtf on 2017/2/7. // Copyright © 2017年 ftf. All rights reserved. // import UIKit import SafariServices class HomeViewController: BaseViewController { @IBOutlet weak var tableView: UITableView! var getDate:Date = Date() var dataArray:[DataListModel]? { didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() launchAnimation() automaticallyAdjustsScrollViewInsets = false tableView.separatorStyle = .none //最底部的空间,设置距离底部的间距(autolayout),然后再设置这两个属性,就可以自动计算高度 tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(self.loadNew)) tableView.mj_header = header tableView.mj_header.beginRefreshing() } func loadNew() { GankooApi.shareInstance.getHomeData(date:getDate) { ( result : [DataListModel]?, error : NSError?) in self.endReresh() if error == nil{ self.dataArray = result }else{ } } } func endReresh(){ self.tableView.mj_header.endRefreshing() self.tableView.mj_header.isHidden = true // self.tableView.mj_footer.endRefreshing() } @IBAction func dateAction(_ sender: UIBarButtonItem) { datePickAction() } func datePickAction() { let current = Date() let min = Date().addingTimeInterval(-60 * 60 * 24 * 15) let max = Date().addingTimeInterval(60 * 60 * 24 * 15) let picker = DateTimePicker.show(selected: current, minimumDate: min, maximumDate: max) picker.highlightColor = UIColor(red: 255.0/255.0, green: 138.0/255.0, blue: 138.0/255.0, alpha: 1) picker.doneButtonTitle = "!! DONE DONE !!" picker.todayButtonTitle = "Today" picker.completionHandler = { date in // self.current = date self.getDate = date self.loadNew() } } } extension HomeViewController : UITableViewDataSource,UITableViewDelegate{ func numberOfSections(in tableView: UITableView) -> Int { noDataView.isHidden = !(dataArray?.count == 0) return dataArray?.count ?? 0; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let array = dataArray?[section].dataArray return array?.count ?? 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = DataSectionHeaderView.headerWithTableView(tableView: tableView) let listModel = dataArray?[section] header.title = listModel?.name return header } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0000001 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = DataListCell.cellWithTableView(tableView: tableView) let listModel = dataArray?[indexPath.section] let model = listModel?.dataArray?[indexPath.row] cell.model = model return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let listModel = dataArray?[indexPath.section] let model = listModel?.dataArray?[indexPath.row] guard let urlStr = model?.url else { return } let url = URL(string: urlStr) let vc = DataDetailController(url: url!, entersReaderIfAvailable: true) vc.model = model present(vc, animated: true, completion: nil) tableView.deselectRow(at: indexPath, animated: true) } } extension HomeViewController { //播放启动画面动画 func launchAnimation() { //获取启动视图 let vc = UIStoryboard(name: "LaunchScreen", bundle: nil) .instantiateViewController(withIdentifier: "launch") let launchview = vc.view! let delegate = UIApplication.shared.delegate delegate?.window!!.addSubview(launchview) //self.view.addSubview(launchview) //如果没有导航栏,直接添加到当前的view即可 //播放动画效果,完毕后将其移除 UIView.animate(withDuration: 1, delay: 1.2, options: .curveLinear, animations: { launchview.alpha = 0.0 let transform = CATransform3DScale(CATransform3DIdentity, 1.5, 1.5, 1.0) launchview.layer.transform = transform }) { (finished) in launchview.removeFromSuperview() } } }
apache-2.0
f0bc2e6ff9038fdc0aeccc2459885f52
30.56129
109
0.623671
4.800785
false
false
false
false
isRaining/Swift30days
1_day/常量与变量/常量与变量/ViewController.swift
1
863
// // ViewController.swift // 常量与变量 // // Created by 张正雨 on 2017/5/16. // Copyright © 2017年 张正雨. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. demo() demo2() } func demo() -> () { //let 定义常量,定义之后不能修改 let x = 10 //var 定义变量,定义之后可以修改 var y = Double(x)/10.0 //自动创建对应类型 let v = UIView() print(x) print("\n") print(y) print(v) } func demo2() { let x: Double = 10 let y: Double = 11.5 print(#function) print(x+y) } }
mit
2a4480bf40e3568cf5503edd04e7fb1f
16.906977
80
0.497403
3.666667
false
false
false
false
twostraws/HackingWithSwift
SwiftUI/project19/SnowSeeker/Facility.swift
1
1269
// // Facility.swift // SnowSeeker // // Created by Paul Hudson on 25/01/2022. // import SwiftUI struct Facility: Identifiable { let id = UUID() var name: String private let icons = [ "Accommodation": "house", "Beginners": "1.circle", "Cross-country": "map", "Eco-friendly": "leaf.arrow.circlepath", "Family": "person.3" ] private let descriptions = [ "Accommodation": "This resort has popular on-site accommodation.", "Beginners": "This resort has lots of ski schools.", "Cross-country": "This resort has many cross-country ski routes.", "Eco-friendly": "This resort has won an award for environmental friendliness.", "Family": "This resort is popular with families." ] var icon: some View { if let iconName = icons[name] { return Image(systemName: iconName) .accessibilityLabel(name) .foregroundColor(.secondary) } else { fatalError("Unknown facility type: \(name)") } } var description: String { if let message = descriptions[name] { return message } else { fatalError("Unknown facility type: \(name)") } } }
unlicense
6c241f0ba384174537981e12b6dda140
26
87
0.57368
4.258389
false
false
false
false
lee0741/Glider
Glider/Story.swift
1
3547
// // Story.swift // Glider // // Created by Yancen Li on 2/24/17. // Copyright © 2017 Yancen Li. All rights reserved. // import Foundation enum StoryType: String { case news = "Hacker News" case best = "Best" case newest = "Newest" case ask = "Ask HN" case show = "Show HN" case jobs = "Jobs" case noobstories = "Noob Stories" case search } struct Story { let id: Int let title: String let time_ago: String let comments_count: Int let url: String let domain: String var points: Int? var user: String? init(from json: [String: Any]) { // for noob and best type if let id = json["id"] as? Int { self.id = id } else { self.id = Int(json["id"] as! String)! } self.title = json["title"] as! String self.time_ago = json["time_ago"] as! String self.comments_count = json["comments_count"] as! Int // for jobs type self.points = json["points"] as? Int self.user = json["user"] as? String let url = json["url"] as! String if url.hasPrefix("item?id=") { self.url = "https://news.ycombinator.com/\(url)" self.domain = "news.ycombinator.com" } else { self.url = url self.domain = url.components(separatedBy: "/")[2] } } init(searchResponse: [String: Any]) { self.id = Int(searchResponse["objectID"] as! String)! self.title = searchResponse["title"] as! String self.points = searchResponse["points"] as? Int self.user = searchResponse["author"] as? String let timestamp = searchResponse["created_at_i"] as! Double self.time_ago = dateformatter(date: timestamp) if let url = searchResponse["url"] as? String { self.url = url self.domain = url.components(separatedBy: "/")[2] } else { self.url = "https://news.ycombinator.com/item/\(self.id))" self.domain = "news.ycombinator.com" } if let comments_count = searchResponse["num_comments"] as? Int { self.comments_count = comments_count } else { self.comments_count = 0 } } } extension Story { static func getStories(type: StoryType, query: String, pagination: Int, completion: @escaping ([Story]) -> Void) { var url: URL! if type == .search { var encodeUrl = URLComponents(string: "https://hn.algolia.com/api/v1/search_by_date?tags=story&hitsPerPage=100") encodeUrl?.queryItems?.append(URLQueryItem(name: "query", value: query)) url = encodeUrl?.url } else { url = URL(string: "https://glider.herokuapp.com/\(type)?page=\(pagination)")! } URLSession.shared.dataTask(with: url) { (data, response, error) in var stories = [Story]() if let error = error { print("Failed to fetch data: \(error)") return } guard let data = data else { return } if type == .search { if let rawData = try? JSONSerialization.jsonObject(with: data, options: []) as! [String: Any], let rawStories = rawData["hits"] as? [[String: Any]] { rawStories.forEach { rawStroy in stories.append(Story.init(searchResponse: rawStroy)) } } } else { if let rawStories = try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]] { rawStories.forEach { rawStroy in stories.append(Story.init(from: rawStroy)) } } } DispatchQueue.main.async { completion(stories) } }.resume() } }
mit
686faa94eb919bdfe078b836e110600b
26.488372
118
0.591089
3.651905
false
false
false
false
greycats/Greycats.swift
Greycats/Breadcrumb.swift
1
5657
// // Breadcrumb.swift // Greycats // // Created by Rex Sheng on 2/2/15. // Copyright (c) 2015 Interactive Labs. All rights reserved. // // available in pod 'Greycats', '~> 0.1.5' import Foundation import UIKit public protocol BreadcrumbPipeline { func process(_ string: NSMutableAttributedString, ranges: [NSRange]) } public protocol Breadcrumb: NSCoding { } public struct BreadcrumbHighlightPipeline: BreadcrumbPipeline { public let attributes: [NSAttributedString.Key: Any] public let pattern: NSRegularExpression public func process(_ string: NSMutableAttributedString, ranges: [NSRange]) { if let range = ranges.last { pattern.matches(in: string.string, options: [], range: range).forEach { match in for i in 1..<match.numberOfRanges { string.addAttributes(attributes, range: match.range(at: i)) } } } } } public struct BreadcrumbTrailingPipeline: BreadcrumbPipeline { public let trailingString: String public let attributes: [NSAttributedString.Key: Any] public let maxSize: CGSize func fit(_ attr: NSAttributedString) -> Bool { let rect = attr.boundingRect(with: CGSize(width: maxSize.width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) // println("\"\(attr.string)\" rect = \(rect)") return rect.size.height <= maxSize.height } public func process(_ string: NSMutableAttributedString, ranges: [NSRange]) { let suffix = NSAttributedString(string: trailingString, attributes: attributes) if fit(string) { return } for range in ranges { string.deleteCharacters(in: NSRange(location: 0, length: range.length)) string.insert(suffix, at: 0) if fit(string) { return } else { string.deleteCharacters(in: NSRange(location: 0, length: suffix.length)) } } } } extension NSAttributedString { public convenience init<T: Breadcrumb>(elements: [T], attributes: [NSAttributedString.Key: Any], transform: @escaping (T) -> String, separator: String, pipelines: [BreadcrumbPipeline]?) { let string = NSMutableAttributedString() let slash = NSAttributedString(string: separator, attributes: attributes) let lastIndex = elements.count - 1 func attributedStringWithEncodedData(_ t: T) -> NSAttributedString { let str = transform(t) var attr = attributes let data = NSMutableData() let coder = NSKeyedArchiver(forWritingWith: data) t.encode(with: coder) coder.finishEncoding() attr[NSAttributedString.Key("archived-data")] = data // attr["archived-data"] = data return NSMutableAttributedString(string: str, attributes: attr) } let ranges: [NSRange] = elements.enumerated().map { index, element in let text = attributedStringWithEncodedData(element) let loc = string.length string.append(text) if index != lastIndex { string.append(slash) return NSRange(location: loc, length: text.length + 1) } else { return NSRange(location: loc, length: text.length) } } pipelines?.forEach { $0.process(string, ranges: ranges) } self.init(attributedString: string) } public func breadcrumbData<T: Breadcrumb>(atIndex index: Int) -> T? { if let value = attribute(NSAttributedString.Key(rawValue: "archived-data"), at: index, effectiveRange: nil) as? Data { let coder = NSKeyedUnarchiver(forReadingWith: value) return T(coder: coder) } return nil } } class Tap { var block: ((UIGestureRecognizer) -> Void)? @objc func tapped(_ tap: UITapGestureRecognizer!) { block?(tap) } } extension UITextView { public func tapOnBreadcrumb<T: Breadcrumb>(_ clousure: @escaping (T) -> Void) -> Any { let tap = Tap() addGestureRecognizer(UITapGestureRecognizer(target: tap, action: #selector(Tap.tapped))) tap.block = {[weak self] tap in guard let container = self else { return } var loc = tap.location(in: container) loc.x -= container.textContainerInset.left loc.y -= container.textContainerInset.top let index = container.layoutManager.characterIndex(for: loc, in: container.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) if index < container.textStorage.length { if let t: T = container.attributedText.breadcrumbData(atIndex: index) { clousure(t) } } } return tap } } open class Breadcrumbs<T: Breadcrumb> { let attributeGenerator: ([T]) -> NSAttributedString weak var container: UITextView! let tap: Any public init(attributes: [NSAttributedString.Key: Any], transform: @escaping (T) -> String, container: UITextView, onClick: @escaping (T) -> Void, separator: String = " / ", pipelines: [BreadcrumbPipeline]? = nil) { self.container = container attributeGenerator = { elements in NSAttributedString(elements: elements, attributes: attributes, transform: transform, separator: separator, pipelines: pipelines) } tap = container.tapOnBreadcrumb(onClick) } open func build(_ breadcrumbs: [T]) { container.attributedText = attributeGenerator(breadcrumbs) } }
mit
9e1a25fc6463d2f0c9b00c0f0ec87876
36.217105
218
0.629662
4.702411
false
false
false
false
Msr-B/Msr.LibSwift
UI/MSRKeyboardBar.swift
2
2129
import UIKit @objc class MSRKeyboardBar: UIView { var backgroundView: UIView? { didSet { oldValue?.removeFromSuperview() if backgroundView != nil { addSubview(backgroundView!) sendSubviewToBack(backgroundView!) backgroundView!.frame = bounds backgroundView!.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] } } } convenience init() { self.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) msr_initialize() } override init(frame: CGRect) { super.init(frame: frame) msr_initialize() } func msr_initialize() { translatesAutoresizingMaskIntoConstraints = false NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) } override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if superview != nil { msr_removeHorizontalEdgeAttachedConstraintsFromSuperview() } } override func didMoveToSuperview() { super.didMoveToSuperview() if superview != nil { msr_addHorizontalEdgeAttachedConstraintsToSuperview() msr_addBottomAttachedConstraintToSuperview() } } internal func keyboardWillChangeFrame(notification: NSNotification) { updateFrame(notification, completion: nil) } private func updateFrame(notification: NSNotification, completion: ((Bool) -> Void)?) { let info = MSRAnimationInfo(keyboardNotification: notification) let bottom = min((superview?.bounds.height ?? 0) - info.frameEnd.msr_top, info.frameEnd.height) info.animate() { [weak self] in self?.transform = CGAffineTransformMakeTranslation(0, -bottom) self?.layoutIfNeeded() return } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
gpl-2.0
f049e2944181cf8627ef685f25d3c08c
35.084746
158
0.637858
5.602632
false
false
false
false