text stringlengths 8 1.32M |
|---|
//
// ProfileAddCType.swift
// KindCer
//
// Created by Muhammad Tafani Rabbani on 06/12/19.
// Copyright © 2019 Muhammad Tafani Rabbani. All rights reserved.
//
import SwiftUI
struct ProfileAddCType: View {
@State var name:String = ""
@State var tanggal:Date = Date()
@ObservedObject var typeModel : CancerModel
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var dateClosedRange: ClosedRange<Date> {
let min = Calendar.current.date(byAdding: .year, value: -2, to: Date())!
let max = Calendar.current.date(byAdding: .year, value: 0, to: Date())!
return min...max
}
var body: some View {
VStack{
ZStack {
headerModal(title: "Jenis Kanker")
HStack{
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Batal").foregroundColor(.white).padding(4)
}.padding(16)
Spacer()
Button(action: {
self.typeModel.saveData(name: self.name, tanggal: self.tanggal)
self.typeModel.readData()
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Simpan").foregroundColor(.white).padding(4)
}.padding(16)
}
}
Form{
Section(header: HStack {
Image("cancertype").resizable().frame(width: 20, height: 20)
Text("Jenis Kanker").font(.headline)
}) {
TextField("Jenis Kanker", text: $name).textFieldStyle(RoundedBorderTextFieldStyle()).padding(.horizontal)
}
Section(header: HStack {
Image("diagnosis").resizable().frame(width: 20, height: 20)
Text("Tanggal Diagnosis").font(.headline)
}) {
DatePicker(
selection: self.$tanggal,
in: self.dateClosedRange,
displayedComponents: .date,
label: { Text("Tanggal Diagnosis").foregroundColor(.clear) .font(.system(size: 15)) .opacity(0.5) }
).labelsHidden()
}
}
Spacer()
}.background(Color("inActive"))
}
}
struct ProfileAddCType_Previews: PreviewProvider {
static var previews: some View {
ProfileAddCType(typeModel: CancerModel())
}
}
|
import UIKit
final class KeyboardFuncCell: UICollectionViewCell {
@IBOutlet var imageIcon: UIImageView!
@IBOutlet var labelName: UILabel!
}
|
//
// AmplifyEvent.swift
// Schuylkill-App
//
// Created by Sam Hicks on 3/6/21.
//
import Amplify
import Foundation
public enum AmplifyMutationEvent: Event {
case mutationEvent(MutationEvent)
}
public enum AuthenticationEvent: Event {
case started
case mutationEvent(MutationEvent)
}
|
import UIKit
import SwiftUI
class ContentViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBSegueAction func addSwiftUIView(_ coder: NSCoder) -> UIViewController? {
return UIHostingController(coder: coder, rootView: ContentView())
}
}
|
//
// AppDelegate.swift
// MVVM
//
// Created by Gleb Tarasov on 09/08/2018.
// Copyright © 2018 Gleb Tarasov. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private let router = Router()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window?.rootViewController = router.rootViewController()
return true
}
}
|
//
// PropertyImagesViewController+PhotoImport.swift
// SweepBright
//
// Created by Kaio Henrique on 4/12/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import Foundation
extension PropertyImagesViewController {
//MARK: Connecting the IBAction to photoSelectorController actions
@IBAction func takePhoto(sender: AnyObject) {
let customAlert = SweepBrightActionSheet()
customAlert.addDefaultAction("Ask Photographer", handler: nil)
customAlert.addDefaultAction("Open Library", handler: {
_ in
self.photoSelectorController.selectPhotoFromLibrary()
})
customAlert.addDefaultAction("Use Camera", handler: {
_ in
self.photoSelectorController.selectPhotoFromCamera()
})
customAlert.addDestructiveAction("Cancel", handler: nil)
customAlert.show(self)
}
@IBAction func takePicture(sender: AnyObject) {
self.photoSelectorController.takePhoto()
}
@IBAction func cancelPhoto(sender: AnyObject) {
self.photoSelectorController.cancelPhotoFromPicker()
}
}
|
//
// SpacingCustomizationViewController.swift
// Demo
//
// Created by Gil Birman on 6/9/20.
// Copyright © 2020 Kyle Van Essen. All rights reserved.
//
import UIKit
import ListableUI
import BlueprintUI
import BlueprintUICommonControls
import BlueprintUILists
final class SpacingCustomizationViewController : UIViewController
{
let listView = ListView()
override func loadView()
{
self.view = self.listView
self.listView.configure { list in
list.layout = .table {
$0.bounds = .init(padding: UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0))
$0.layout.set {
$0.itemSpacing = 20.0
$0.interSectionSpacingWithFooter = 20.0
$0.interSectionSpacingWithNoFooter = 20.0
}
}
list += Section("default") { section in
section += Item(
CardElement(title: "Default Row In Default Section", color: .white(0.95)),
sizing: .thatFits()
)
}
list += Section("custom-50") { section in
section.layouts.table = .init(customInterSectionSpacing: 50)
section += Item(
CardElement(title: "Default Row In 50 Spacing Section", color: .white(0.95)),
sizing: .thatFits()
)
}
list += Section("custom-100") { section in
section.layouts.table = .init(customInterSectionSpacing: 100)
section += Item(
CardElement(title: "Default Row In 100 Spacing Section", color: .white(0.95)),
sizing: .thatFits()
)
}
list += Section("default-2") { section in
section += Item(
CardElement(title: "Default Row In another Default Section", color: .white(0.95)),
sizing: .thatFits()
)
}
}
}
}
fileprivate struct CardElement : BlueprintItemContent, Equatable
{
var title : String
var color : UIColor
//
// MARK: BlueprintItemElement
//
var identifierValue: String {
self.title
}
func element(with info : ApplyItemContentInfo) -> Element
{
return Box(
backgroundColor: self.color,
cornerStyle: .rounded(radius: 5.0),
wrapping: Inset(uniformInset: 10.0, wrapping: Label(text: self.title) {
$0.font = .systemFont(ofSize: 16.0, weight: .bold)
})
)
}
}
|
//
// ViewController.swift
// HelloPlaySystemSound
//
// Created by mikewang on 2017/9/17.
// Copyright © 2017年 mike. All rights reserved.
//
import UIKit
import AudioToolbox
class ViewController: UIViewController {
@IBAction func play(_ sender: UIButton) {
for i in 1000...1030 {
print("\(i)")
AudioServicesPlaySystemSound(SystemSoundID(i))
sleep(2)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
// Copyright © 2019 Pablo Mateos García. All rights reserved.
import Foundation
class Diccionario{
var silabas : [Silaba] = []
func añadirSilaba(silaba : Silaba) -> Void{
silabas.append(silaba)
}
func returnSilabas() -> [Silaba]{
return silabas
}
func jpToRomanji(jp:String)->String{
let silabas = self.returnSilabas()
for i in silabas{
if(i.jp == jp){
return i.romanji
}
}
return ""
}
func romanjiToJp(romanji:String)->String{
let silabas = self.returnSilabas()
for i in silabas{
if(i.romanji == romanji){
return i.jp
}
}
return ""
}
}
|
//
// SocketIOManager.swift
// DrawAndGuess
//
// Created by Troy on 2017/2/3.
// Copyright © 2017年 Huanyan's. All rights reserved.
//
import UIKit
import SocketIO
class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()
override init() {
super.init()
}
var socket = SocketIOClient(socketURL: URL(string: "http://160.39.237.216:4000")!)
func establishConnection() {
socket.connect()
}
func closeConnection() {
socket.disconnect()
}
func nextRound() {
socket.emit("nextRound")
}
func drawLine(fromX:Double, fromY:Double, toX:Double, toY:Double) {
socket.emit("drawLine", fromX, fromY, toX, toY)
}
func resetCanvas() {
socket.emit("resetCanvas")
}
func sendGuess(guess:String) {
socket.emit("sendGuess", guess, UserDefaults.standard.string(forKey: "userID")!)
}
func receiveDrawLine(completionHandler:@escaping (_ points:[Double]) -> Void) {
socket.on("receiveDrawLine", callback: {(dataArray, socketAck) in
completionHandler(dataArray as! [Double])
})
}
func receiveResetCanvas(completionHandler:@escaping () -> Void) {
socket.on("receiveResetCanvas", callback: {(dataArray, socketAck) in
completionHandler()
})
}
func receiveSendGuess(completionHandler:@escaping (_ guess:String, _ userID:String, _ verdict:String) -> Void) {
socket.on("receiveSendGuess", callback: {(dataArray, socketAck) in
completionHandler(dataArray[0] as! String,dataArray[1] as! String,dataArray[2] as! String)
})
}
func receiveStartNewRound(completionHandler:@escaping (_ roundCount:Int, _ keyword:String, _ hint:String, _ drawingUser:String) -> Void) {
socket.on("receiveStartNewRound", callback: {(dataArray, socketAck) in
completionHandler(dataArray[0] as! Int, dataArray[1] as! String,dataArray[2] as! String, dataArray[3] as! String)
})
}
func receiveStartNewGame(completionHandler:@escaping () -> Void) {
socket.on("receiveStartNewGame", callback: {(dataArray, socketAck) in
completionHandler()
})
}
func receiveUsers(completionHandler:@escaping (_ users:[[String:Any]]) -> Void) {
socket.on("receiveUsers", callback: {(dataArray, socketAck) in
completionHandler(dataArray[0] as! [[String: Any]])
})
}
func receiveRevealAnswer(completionHandler:@escaping () -> Void) {
socket.on("receiveRevealAnswer", callback: {(dataArray, socketAck) in
completionHandler()
})
}
func receiveAddScoreToDrawingUser(completionHandler:@escaping () -> Void) {
socket.on("receiveAddScoreToDrawingUser", callback: {(dataArray, socketAck) in
completionHandler()
})
}
func connectUser(userID: String, avatar:NSData) {
print("Connecting to server")
socket.emit("connectUser", userID, avatar)
}
func disConnectUser(userID: String) {
socket.emit("exitUser", userID)
}
}
|
//
// YelpClient
// SurpriseMe
//
// Created by Evan Grossman on 8/19/16.
// Copyright © 2016 Evan Grossman. All rights reserved.
//
import Alamofire
import RxSwift
import SwiftyJSON
class YelpClient {
static let YelpBaseURL = "https://api.yelp.com/v3/"
static func searchForLocation(latitude: Double, longitude: Double, token: String) -> Observable<[SMLocation]> {
return Observable.create { o in
var urlComponents = baseURLComponents()
urlComponents.path = "/v3/businesses/search"
urlComponents = addQueryToURLComponents(urlComponents, name: "latitude", value: String(latitude))
urlComponents = addQueryToURLComponents(urlComponents, name: "longitude", value: String(longitude))
let defaultSearchOptions = SMSearchOptions()
urlComponents = addQueryToURLComponents(urlComponents, name: "term", value: defaultSearchOptions.term)
let sortOption = defaultSearchOptions.sort
urlComponents = addQueryToURLComponents(urlComponents, name: "sort", value: sortOption.rawValue)
if sortOption == .HighestRated || sortOption == .Closest {
urlComponents = addQueryToURLComponents(urlComponents, name: "limit", value: "10")
}
urlComponents = addQueryToURLComponents(urlComponents, name: "radius", value: defaultSearchOptions.radius.rawValue)
Alamofire.request(.GET, urlComponents.URL!, headers: ["Authorization": "Bearer \(token)"])
.responseJSON { (response) in
switch response.result {
case .Success(let data):
let json = JSON(data)
let locations = YelpLocationParser.parseLocationsFromJSON(json)
o.onNext(locations)
o.onCompleted()
break
case .Failure:
o.onError(Error.RequestFailed)
}
}
return AnonymousDisposable { }
}
}
private static func baseURLComponents() -> NSURLComponents {
let urlComponents = NSURLComponents()
urlComponents.scheme = "https";
urlComponents.host = "api.yelp.com";
return urlComponents;
}
private static func addQueryToURLComponents(urlComponents: NSURLComponents, name: String, value: String) -> NSURLComponents {
let query = NSURLQueryItem(name: name, value: value)
if urlComponents.queryItems == nil {
urlComponents.queryItems = []
}
urlComponents.queryItems?.append(query)
return urlComponents
}
}
|
class Solution {
func maxPathSum(_ root: TreeNode?) -> Int {
let (ret, _) = helper(root)
return ret
}
// 第一个返回全局最大,第二个返回单路径最大
func helper(_ root: TreeNode?) -> (Int, Int){
guard let root = root else {
return (Int.min, Int.min)
}
let (l1, l2) = helper(root.left)
let (r1, r2) = helper(root.right)
let single_max = max(root.val, root.val + max(l2, r2, 0))
let global_max = max(single_max, root.val + max(l2, 0) + max(r2, 0), l1, r1)
return (global_max, single_max)
}
} |
//
// WorkoutDetailSeparatorCell.swift
// iOS-TraningsDagboken
//
// Created by Eddy Garcia on 2018-09-25.
// Copyright © 2018 Eddy Garcia. All rights reserved.
//
import UIKit
class WorkoutDetailSeparatorCell: UITableViewCell {
@IBOutlet var titleLabel : UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// Rect+Extension.swift
// MJExtension
//
// Created by chenminjie on 2020/11/7.
//
import Foundation
extension TypeWrapperProtocol where WrappedType == CGRect {
public func reset(width: CGFloat) -> CGRect {
return reset(size: CGSize(width: width, height: wrappedValue.size.height))
}
public func reset(height: CGFloat) -> CGRect {
return reset(size: CGSize(width: wrappedValue.size.width, height: height))
}
public func reset(size: CGSize) -> CGRect {
var rect = wrappedValue
rect.size = size
return rect
}
public func reset(x: CGFloat) -> CGRect {
return reset(origin: CGPoint(x: x, y: wrappedValue.origin.y))
}
public func reset(y: CGFloat) -> CGRect {
return reset(origin: CGPoint(x: wrappedValue.origin.x, y: y))
}
public func reset(origin: CGPoint) -> CGRect {
var rect = wrappedValue
rect.origin = origin
return rect
}
}
|
//
// ChatingTableViewCell.swift
// ClassyDrives
//
// Created by apple on 27/08/19.
// Copyright © 2019 Mindfull Junkies. All rights reserved.
//
import UIKit
class ChatingTableViewCell: UITableViewCell {
@IBOutlet weak var mSenderTimeLbl: UILabel!
@IBOutlet weak var mSenderLbl: UILabel!
@IBOutlet weak var mReciverTimeLbl: UILabel!
@IBOutlet weak var mReciverLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// CollectionTestVC.swift
// Sopt_iOS_Assignment
//
// Created by 김민희 on 2020/11/04.
//
import UIKit
class CollectionTestVC: UIViewController {
@IBOutlet weak var soptCollectionView: UICollectionView!
@IBOutlet weak var writeButton: UIButton!
@IBOutlet weak var headerView: UIView!
private var profileList: [Profile] = []
override func viewDidLoad() {
super.viewDidLoad()
setProfile()
writeButton.layer.cornerRadius = 8
soptCollectionView.dataSource = self
soptCollectionView.delegate = self
// Do any additional setup after loading the view.
}
private func setProfile() {
let profile1 = Profile(profileImageName: "WCB_MH", name: "김민희", tag: "#딩초 #ENTP #유튜브 #왕초보 #근본")
let profile2 = Profile(profileImageName: "WCB_YJ", name: "최영재", tag: "#🦮 #아요2회차 #왕초보 #민초단 #문이과대통합")
let profile3 = Profile(profileImageName: "WCB_JH", name: "송지훈", tag: "#28살처럼보이지만 #24살맞습니다^^ #모각공환영 #술자리환영")
let profile4 = Profile(profileImageName: "WCB_JE", name: "황지은", tag: "#보라돌이 #ISFP #운팀2회차 #왕초보진심녀 #취중고백장인")
let profile5 = Profile(profileImageName: "WCB_YS", name: "이예슬", tag: "#개발자 #ESFJ #몽글 #집사 #아요왕초보스터디")
let profile6 = Profile(profileImageName: "WCB_SJ", name: "이수진", tag: "#테트리수진 #하드유저 #서브남주 #동물의숲_페이커 #맥시멀리스트")
let profile7 = Profile(profileImageName: "WCB_SH", name: "류세화", tag: "#밈꿈나무 #지옥에서온민초단 #뇌절마스터")
let profile8 = Profile(profileImageName: "WCB_BUDDY", name: "버디", tag: "#고구마성애자 #남자였음 #한창미운9살 #사람나이로63 #귀차니즘")
profileList = [profile1,profile2,profile3,profile4,profile5,profile6,profile7,profile8]
}
}
extension CollectionTestVC: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return profileList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SoptWorkingCell.identifier, for: indexPath) as? SoptWorkingCell else {
return UICollectionViewCell() }
cell.setProfile(profileList[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerview = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SoptCollectionHeader", for: indexPath) as! SoptCollectionHeader
return headerview
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: self.view.frame.width, height: self.view.frame.width*(420/375))
}
}
extension CollectionTestVC: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt
indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionView.frame.width-48-27) / 2,
height: (collectionView.frame.width-48-27) / 2 + 75)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0 }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 27
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 41, left: 24, bottom: 0, right: 24) }
}
extension CollectionTestVC: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.headerView.frame.origin.y = -100
}
}
|
//
// NearByController.swift
// Swift-Base
//
// Created by Peerapun Sangpun on 5/15/2559 BE.
// Copyright © 2559 Flatstack. All rights reserved.
//
import UIKit
import RealmSwift
class PropertyCell: UITableViewCell {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDescription: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ListController : UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
var contacts:Results<Contact>?
var filtered:Results<Contact>?
var data: NSArray?
var searchActive : Bool = false
@IBOutlet weak var tableView: UITableView!
var resultSearchController = UISearchController()
//@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
//self.hideKeyboardWhenTappedAround()
tableView.delegate = self
tableView.dataSource = self
//searchBar.delegate = self
do {
let realm = try Realm()
contacts = realm.objects(Contact)
} catch let error as NSError {
// handle error
}
if #available(iOS 9.0, *) {
self.resultSearchController.loadViewIfNeeded()// iOS 9
} else {
// Fallback on earlier versions
let _ = self.resultSearchController.view // iOS 8
}
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.hidesNavigationBarDuringPresentation = true
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.searchBarStyle = .Minimal
controller.searchBar.sizeToFit()
controller.searchResultsUpdater = self
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
self.tableView.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
if searchController.searchBar.text?.characters.count > 0 {
let predicate = NSPredicate(format: "name CONTAINS [c]%@", searchController.searchBar.text!);
do {
filtered = try Realm().objects(Contact).filter(predicate).sorted("name", ascending: true)
} catch {
}
}
else {
filtered = contacts
}
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.resultSearchController.active {
return filtered!.count
}
return (contacts?.count)!;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as! PropertyCell
let contact: Contact?
if(self.resultSearchController.active){
contact = filtered![indexPath.row] as Contact
} else {
contact = contacts![indexPath.row] as Contact
}
//let contact: Contact = self.data![indexPath.row] as! Contact
cell.lblTitle?.text = String(contact!.name)
cell.lblDescription?.text = contact!.address
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "goDetail" {
let destination = segue.destinationViewController as? DetailController
let contact: Contact?
let index = tableView.indexPathForSelectedRow?.row
if(self.resultSearchController.active){
contact = filtered![index!] as Contact
} else {
contact = contacts![index!] as Contact
}
destination?.contact = contact
}
}
}
|
//
// CardListCell.swift
// Qvafy
//
// Created by ios-deepak b on 26/06/20.
// Copyright © 2020 IOS-Aradhana-cat. All rights reserved.
//
import UIKit
class CardListCell: UITableViewCell {
@IBOutlet var vwContainer: UIView!
@IBOutlet var vwImageContainer: UIView!
@IBOutlet var lblCardNumber: UILabel!
@IBOutlet var lblCardAddDate: UILabel!
@IBOutlet var imgVwCardType: UIImageView!
@IBOutlet var imgCheck: UIImageView!
@IBOutlet var btnCheck: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.vwContainer.setShadowWithCornerRadius()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// PlaybackState.swift
// audio_service
//
// Created by Mohamed Abdallah on 3/29/20.
//
import Foundation
class PlaybackState {
var controls = [RemoteCommand]()
var state: BasicPlaybackState
var position: Int
var updateTime: UInt64
var speed: Double
init() {
let msSinceEpoch = UInt64(Date().timeIntervalSince1970 * 1000)
state = .none
position = 0
updateTime = msSinceEpoch
speed = 1.0
}
init? (arguments: Any?) {
guard let arguments = arguments as? NSArray else {return nil}
let controls = arguments[0] as? [[String:Any]] ?? []
let systemActions = arguments[1] as? [Int] ?? []
state = BasicPlaybackState(rawValue: arguments[2] as? Int ?? 0) ?? .none
position = arguments[3] as? Int ?? 0
speed = arguments[4] as? Double ?? 1.0
updateTime = arguments[5] as? UInt64 ?? UInt64(Date().timeIntervalSince1970 * 1000)
appendRemoteCommands(controls.compactMap({$0["action"] as? Int}))
appendRemoteCommands(systemActions)
}
func toArguments() -> NSArray {
return [state.rawValue,0,position,speed,updateTime]
}
private func appendRemoteCommands(_ commands: [Int]) {
commands.forEach({
if let mediaAction = mediaActionToRemoteCommand(MediaAction(rawValue: $0)) {
controls.append(mediaAction)
}
})
}
private func mediaActionToRemoteCommand(_ mediaAction: MediaAction?) -> RemoteCommand? {
switch mediaAction {
case .stop:
return .stop
case .pause:
return .pause
case .play:
return .play
case .rewind:
//TODO add preferredIntervals
return .skipBackward(preferredIntervals: [30])
case .skipToPrevious:
return .previous
case .skipToNext:
return .next
case .fastForward:
return .skipForward(preferredIntervals: [30])
case .setRating:
return nil
case .seekTo:
return .changePlaybackPosition
case .playPause:
return .togglePlayPause
case .playFromMediaId:
return nil
case .playFromSearch:
return nil
case .skipToQueueItem:
return nil
case .playFromUri:
return nil
case .none:
return nil
}
}
}
enum BasicPlaybackState:Int {
case none
case stopped
case paused
case playing
case fastForwarding
case rewinding
case buffering
case error
case connecting
case skippingToPrevious
case skippingToNext
case skippingToQueueItem
}
/// The actons associated with playing audio.
public enum MediaAction: Int {
case stop
case pause
case play
case rewind
case skipToPrevious
case skipToNext
case fastForward
case setRating
case seekTo
case playPause
case playFromMediaId
case playFromSearch
case skipToQueueItem
case playFromUri
}
|
//
// GZEProfileViewController.swift
// Gooze
//
// Created by Yussel on 2/22/18.
// Copyright © 2018 Gooze. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
class GZEProfileViewController: UIViewController {
let segueToUpdateProfile = "segueToUpdateProfile"
var viewModel: GZEProfileUserInfoViewModel!
@IBOutlet weak var scrollContentView: UIView!
@IBOutlet weak var usernameLabel: GZELabel!
@IBOutlet weak var phraseLabel: GZELabel!
@IBOutlet weak var genderLabel: GZELabel!
@IBOutlet weak var ageLabel: GZELabel!
@IBOutlet weak var heightLabel: GZELabel!
@IBOutlet weak var weightLabel: GZELabel!
@IBOutlet weak var originLabel: GZELabel!
@IBOutlet weak var languagesLabel: GZELabel!
@IBOutlet weak var interestsLabel: GZELabel!
@IBOutlet weak var genderButton: UIButton!
@IBOutlet weak var ageButton: UIButton!
@IBOutlet weak var heightButton: UIButton!
@IBOutlet weak var weightButton: UIButton!
@IBOutlet weak var originButton: UIButton!
@IBOutlet weak var languagesButton: UIButton!
@IBOutlet weak var interestsButton: UIButton!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var contactButton: GZEButton!
@IBOutlet weak var editButton: GZEEditButton!
override func viewDidLoad() {
super.viewDidLoad()
log.debug("\(self) init")
setupInterfaceObjects()
setUpBindings()
viewModel.didLoadObs.send(value: ())
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewModel.startObservers()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.viewModel.stopObservers()
}
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.
if segue.identifier == segueToUpdateProfile {
prepareUpdateProfileSegue(segue.destination, vm: sender)
}
}
func prepareUpdateProfileSegue(_ vc: UIViewController, vm: Any?) {
guard let profileVc = vc as? GZESignUpProfileViewController else {
log.error("unexpected segue destination \(vc) expecting GZESignUpProfileViewController")
return
}
guard let profileVm = vm as? GZEUpdateProfileViewModel else {
log.error("unexpected segue sender \(String(describing: vm)), expecting GZEUpdateProfileViewModel")
return
}
profileVm.dismiss = {
}
profileVc.viewModel = profileVm
profileVc.scene = .editProfile
}
private func setupInterfaceObjects() {
navigationItem.hidesBackButton = true
usernameLabel.setWhiteFontFormat()
phraseLabel.setWhiteFontFormat()
genderLabel.setWhiteFontFormat()
ageLabel.setWhiteFontFormat()
heightLabel.setWhiteFontFormat()
weightLabel.setWhiteFontFormat()
originLabel.setWhiteFontFormat()
languagesLabel.setWhiteFontFormat()
//ocupationLabel.setWhiteFontFormat()
interestsLabel.setWhiteFontFormat()
contactButton.enableAnimationOnPressed()
contactButton.setGrayFormat()
}
private func setUpBindings() {
viewModel.error.signal.observeValues { error in
error.flatMap {
GZEAlertService.shared.showBottomAlert(text: $0)
}
}
viewModel.loading
.producer
.startWithValues {[weak self] loading in
guard let this = self else {return}
if loading {
this.showLoading()
} else {
this.hideLoading()
}
}
viewModel.dismissSignal
.observeValues {[weak self] in
guard let this = self else {return}
this.previousController(animated: true)
}
viewModel.segueToUpdateProfile
.observeValues {[weak self] vm in
guard let this = self else {return}
this.performSegue(withIdentifier: this.segueToUpdateProfile, sender: vm)
}
usernameLabel.reactive.text <~ viewModel.username
phraseLabel.reactive.text <~ viewModel.phrase
genderLabel.reactive.text <~ viewModel.gender
ageLabel.reactive.text <~ viewModel.age
heightLabel.reactive.text <~ viewModel.height
weightLabel.reactive.text <~ viewModel.weight
originLabel.reactive.text <~ viewModel.origin
languagesLabel.reactive.text <~ viewModel.languages
//ocupationLabel.reactive.text <~ viewModel.ocupation
interestsLabel.reactive.text <~ viewModel.interestedIn
profileImageView.reactive.noirImageUrlRequestLoading <~ viewModel.profilePic
contactButton.reactive.isHidden <~ viewModel.actionButtonIsHidden
contactButton.reactive.title <~ viewModel.actionButtonTitle
contactButton.reactive.pressed = viewModel.bottomButtonAction
genderButton.reactive.pressed = viewModel.genderAction.value
ageButton.reactive.pressed = viewModel.ageAction.value
heightButton.reactive.pressed = viewModel.heightAction.value
weightButton.reactive.pressed = viewModel.weightAction.value
originButton.reactive.pressed = viewModel.originAction.value
languagesButton.reactive.pressed = viewModel.languagesAction.value
interestsButton.reactive.pressed = viewModel.interestedInAction.value
editButton.reactive.pressed = viewModel.editUserAction.value
editButton.reactive.isHidden <~ viewModel.editUserButtonIsHidden
}
// MARK: - Deinitializers
deinit {
log.debug("\(self) disposed")
}
}
|
//
// ios_userdefaults_sampleTests.swift
// ios-userdefaults-sampleTests
//
// Created by ogasawara_dev on 2018/06/16.
// Copyright © 2018年 ogasawara_dev. All rights reserved.
//
import Foundation
import XCTest
@testable import ios_userdefaults_sample
class ios_userdefaults_sampleTests: XCTestCase {
let userDefaults = UserDefaults.standard
func testDate() {
let expectedDate = Date()
userDefaults[.lastLaunchDate] = expectedDate
let date: Date? = userDefaults[.lastLaunchDate]
XCTAssertEqual(date, expectedDate)
}
func testBool() {
userDefaults[.isEverLaunched] = true
let bool: Bool? = userDefaults[.isEverLaunched]
XCTAssertEqual(bool, true)
}
func testRemove() {
userDefaults[.isEverLaunched] = true
userDefaults.remove(key: .isEverLaunched)
let isEverLaunched: Bool? = userDefaults[.isEverLaunched]
XCTAssertNil(isEverLaunched)
}
}
extension ios_userdefaults_sampleTests {
//ユーザー定義型の保存
func testCustomClass() {
@objc(_TtCFC28ios_userdefaults_sampleTests28ios_userdefaults_sampleTests15testCustomClassFT_T_L_4Team)class Team: NSObject, NSCoding {
var name = String()
override init() {}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
}
}
let team = Team()
let teamName = "あんこう"
team.name = teamName
let userDefaults = UserDefaults.standard
userDefaults.archive(key: "team", value: team)
let value: Team? = userDefaults.unarchive(key: "team")
XCTAssertEqual(value?.name, teamName)
}
}
//UserDefaultsのキーを定義して、区分値をsubscriptに与えればアクセスできるようにする(型名を省略)
enum AppKey: String, Keyable {
case lastLaunchDate
case isEverLaunched
}
extension UserDefaults {
subscript<T: Any>(key: AppKey, defaultValue: T) -> T {
get { return self[key.rawValue, defaultValue] }
set { self[key.rawValue] = newValue }
}
subscript<T: Any>(key: AppKey) -> T? {
get { return self[key.rawValue] }
set { self[key.rawValue] = newValue }
}
func remove(key: AppKey) {
removeObject(forKey: key.rawValue)
}
}
extension String: Keyable {
public var rawValue: String { return self }
}
|
//
// UITableView.swift
// ActionSheetPeerTableViewCellItemExamples
//
// Created by Pavle Ralic on 2/27/20.
// Copyright © 2020 Pavle Ralic. All rights reserved.
//
import UIKit.UITableView
import ActionSheetPeerTableViewCellItem
extension UITableView {
func dequeueReusableCell(withModel model: CellViewAnyModel?, for indexPath: IndexPath, actionSheetDelegate: ActionSheetTableViewCellDelegate?) -> UITableViewCell {
guard
let model = model,
let cell = dequeueReusableCell(withIdentifier: model.identifier, for: indexPath) as? ActionSheetTableViewCell else { return UITableViewCell() }
model.setupDefault(on: cell)
cell.dataProviderProtocol = actionSheetDelegate
return cell
}
}
|
//
// ConvertController.swift
// Valute
//
// Created by Aleksandar Vacić on 26.4.17..
// Copyright © 2017. Radiant Tap. All rights reserved.
//
import UIKit
final class ConvertController: UIViewController {
@IBOutlet weak var sourceCurrencyBox: CurrencyBox!
@IBOutlet weak var targetCurrencyBox: CurrencyBox!
@IBOutlet weak var keypadView: KeypadView!
// Internal data model
fileprivate enum Key: String {
case sourceCC = "sourceCurrencyCode"
case targetCC = "targetCurrencyCode"
}
fileprivate var sourceCurrencyCode: String = "" {
didSet {
UserDefaults.standard.set(sourceCurrencyCode, forKey: Key.sourceCC.rawValue)
sourceCurrencyBox.currencyCode = sourceCurrencyCode
}
}
fileprivate var targetCurrencyCode: String = "" {
didSet {
UserDefaults.standard.set(targetCurrencyCode, forKey: Key.targetCC.rawValue)
targetCurrencyBox.currencyCode = targetCurrencyCode
}
}
fileprivate var activeCurrencyBox: CurrencyBox?
fileprivate var amount: Decimal? {
didSet {
// perform conversion
updateConversionPanel()
}
}
}
// View lifecycle
extension ConvertController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Currency Converter"
configureCurrencyBoxes()
configureKeypad()
populateDataModel()
}
}
extension ConvertController: CurrencyBoxDelegate {
fileprivate func configureCurrencyBoxes() {
sourceCurrencyBox.delegate = self
targetCurrencyBox.delegate = self
sourceCurrencyBox.amount = nil
targetCurrencyBox.amount = nil
}
func currencyBoxRequestsCurrencyChange(_ box: CurrencyBox) {
let storyboard = UIStoryboard(name: "Convert", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: PickerController.storyboardIdentifier) as! PickerController
vc.delegate = self
vc.currencies = ExchangeManager.shared.allowedCurrencies
show(vc, sender: self)
if box == sourceCurrencyBox {
activeCurrencyBox = sourceCurrencyBox
} else {
activeCurrencyBox = targetCurrencyBox
}
}
}
extension ConvertController: PickerControllerDelegate {
func pickerController(_ controller: PickerController, didSelect currencyCode: String) {
self.navigationController?.popViewController(animated: true)
guard let activeCurrencyBox = activeCurrencyBox else {
return
}
// update data model
if activeCurrencyBox == sourceCurrencyBox {
sourceCurrencyCode = currencyCode
} else {
targetCurrencyCode = currencyCode
}
self.activeCurrencyBox = nil
}
}
extension ConvertController: KeypadViewDelegate {
fileprivate func configureKeypad() {
keypadView.delegate = self
}
func keypadView(_ keypad: KeypadView, didChangeAmount value: Decimal?) {
amount = value
}
func keypadView(_ keypad: KeypadView, didChangeValue value: String?) {
sourceCurrencyBox.amountString = value
}
}
fileprivate extension ConvertController {
func populateDataModel() {
if let cc = UserDefaults.standard.value(forKey: Key.sourceCC.rawValue) as? String {
sourceCurrencyCode = cc
} else {
sourceCurrencyCode = sourceCurrencyBox.currencyCode
}
if let cc = UserDefaults.standard.value(forKey: Key.targetCC.rawValue) as? String {
targetCurrencyCode = cc
} else {
targetCurrencyCode = targetCurrencyBox.currencyCode
}
amount = sourceCurrencyBox.amount
}
func updateConversionPanel() {
guard let amount = amount else { return }
ExchangeManager.shared.conversionRate(from: sourceCurrencyCode, to: targetCurrencyCode) {
[weak self] rate, error in
guard let `self` = self else { return }
if let error = error {
DispatchQueue.main.async {
let ac = UIAlertController(title: error.title, message: error.message, preferredStyle: .alert)
let ok = UIAlertAction(title: NSLocalizedString("OK", comment: ""),
style: .default)
ac.addAction(ok)
self.present(ac, animated: true, completion: nil)
}
return
}
guard let rate = rate else { return }
let result = amount * rate
DispatchQueue.main.async {
self.targetCurrencyBox.amount = result
}
}
}
}
|
//
// UIApplication+Extensions.swift
// StashMob
//
// Created by Scott Jones on 8/22/16.
// Copyright © 2016 Scott Jones. All rights reserved.
//
import UIKit
extension UIApplication {
public func navigateToSettings() {
if #available(iOS 8.0, *) {
let url = NSURL(string: UIApplicationOpenSettingsURLString)
openURL(url!)
}
}
}
|
//
// CheckableTableViewCell.swift
// Airstrike
//
// Created by BoHuang on 6/23/17.
// Copyright © 2017 Airstrike. All rights reserved.
//
import UIKit
class CheckableTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var checkSwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setData(_ title: String, checked: Bool) {
titleLabel.text = title
checkSwitch.setOn(checked, animated: false)
}
}
|
//
// SwiftPackageService.swift
// Highway
//
// Created by Stijn on 06/03/2019.
//
import Foundation
import SourceryAutoProtocols
import ZFile
public protocol DumpServiceProtocol: AutoMockable
{
// sourcery:inline:DumpService.AutoGenerateProtocol
func generateDump() throws -> DumpProtocol
// sourcery:end
}
public struct DumpService: DumpServiceProtocol, AutoGenerateProtocol
{
private let swiftPackageFolder: FolderProtocol
private let system: SystemProtocol
private let terminal: TerminalProtocol
public init(swiftPackageFolder: FolderProtocol, system: SystemProtocol = System.shared, terminal: TerminalProtocol = Terminal.shared)
{
self.swiftPackageFolder = swiftPackageFolder
self.terminal = terminal
self.system = system
}
public func generateDump() throws -> DumpProtocol
{
let task = try system.process("swift")
task.arguments = ["package", "dump-package"]
task.currentDirectoryPath = swiftPackageFolder.path
let output: String = try terminal.runProcess(task).joined()
let data = output.data(using: .utf8)!
return try JSONDecoder().decode(Dump.self, from: data)
}
}
|
//
// ReviewsTableViewController.swift
// Experiment Go
//
// Created by luojie on 9/27/15.
// Copyright © 2015 LuoJie. All rights reserved.
//
import Foundation
import CloudKit
class ReviewsTableViewController: CloudKitTableViewController {
var reviewTo: CKExperiment?
override var refreshOperation: GetCKItemsOperation {
return GetReviewsOperation(reviewTo: reviewTo!)
}
override var loadNextPageOperation: GetCKItemsOperation? {
guard let cursor = lastCursor else { return nil }
return GetReviewsOperation(type: .GetNextPage(cursor))
}
// MARK: - Segue
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
guard let segueID = SegueID(rawValue: identifier) else { return true }
guard case .AddReview = segueID else { return true }
guard didAuthoriseElseRequest(didAuthorize: { self.performSegueWithIdentifier(identifier, sender: sender) }) else { return false }
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier else { return }
guard let segueID = SegueID(rawValue: identifier) else { return }
switch segueID {
case .AddReview:
guard let rvc = segue.destinationViewController.contentViewController as? ReviewViewController else { return }
let review = CKLink(reviewTo: reviewTo!)
rvc.review = review
rvc.done = saveReview
case .ShowUserDetail:
guard let udvc = segue.destinationViewController.contentViewController as? UserDetailViewController,
let cell = UITableViewCell.cellForView(sender as! UIButton) as? ReviewTableViewCell else { return }
udvc.user = cell.review?.creatorUser
}
}
func saveReview(review: CKLink) {
items.insert([review], atIndex: 0)
tableView.insertSectionAtIndex(0)
review.saveInBackground(
didFail: {
self.handleFail($0)
let index = self.items.indexOf { $0 == [review] }!
self.items.removeAtIndex(index)
self.tableView.deleteSectionAtIndex(index)
}
)
}
private enum SegueID: String {
case AddReview
case ShowUserDetail
}
} |
// Generated using Sourcery 0.17.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import Domain
import RealmSwift
extension Channel {
static func makeDefault(
feedUrl: URL = URL(string: "http://example.com")!,
title: String = "",
showDescription: String = "",
artwork: URL = URL(string: "http://example.com")!,
categories: [String] = [],
explicit: Bool = false,
language: Language = .english,
author: String? = nil,
site: URL? = nil,
owner: ChannelOwner? = nil
) -> Self {
return .init(
feedUrl: feedUrl,
title: title,
showDescription: showDescription,
artwork: artwork,
categories: categories,
explicit: explicit,
language: language,
author: author,
site: site,
owner: owner
)
}
}
|
//
// StableMarriageProblem.swift
// Algorithms&DataStructures
//
// Created by Paul Kraft on 14.02.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
// swiftlint:disable trailing_whitespace
public class Proposer <Data> {
public var data: Data
public var fiancee: Proposer<Data>?
public var candidates = [Proposer<Data>]()
var candidateIndex = 0
public init(data: Data) { self.data = data }
func rank(of candidate: Proposer<Data>) -> Int {
return candidates.index(where: { candidate === $0 }) ?? candidates.count
}
func prefers(_ newFiancee: Proposer<Data>) -> Bool {
if let f = self.fiancee {
return rank(of: newFiancee) < rank(of: f)
}
return true
}
func nextCandidate() -> Proposer<Data>? {
if candidateIndex >= candidates.count { return nil }
let c = candidates[candidateIndex]
candidateIndex += 1
return c
}
func engage(to guy: Proposer<Data>) {
if let f = guy.fiancee { f.fiancee = nil }
guy.fiancee = self
if let f = self.fiancee { f.fiancee = nil }
self.fiancee = guy
}
}
public func isStable<D>(guys: [Proposer<D>], gals: [Proposer<D>]) -> Bool {
for i in guys.indices {
for j in gals.indices {
if guys[i].prefers(gals[j]) && gals[j].prefers(guys[i]) {
return false
}
}
}
return true
}
public func stableMarriageProblem<D>(proposers guys: [Proposer<D>]) {
var done = true
repeat {
done = true
for guy in guys where guy.fiancee == nil {
done = false
if let gal = guy.nextCandidate() {
if gal.prefers(guy) {
guy.engage(to: gal)
}
}
}
} while !done
}
|
import UIKit
struct FileSave {
}
struct SaveDataConstant {
static let Name:String = "Pixel"
static let Ext:String = "pxl"
}
typealias Const = SaveDataConstant
func shareFile(_ filename:String,presentingVC:UIViewController) {
let saveManager = SaveManager(SaveKey(filename,FileExtension.value))
let activityController = UIActivityViewController(activityItems: ["\(Const.Name) File", saveManager.saveURL], applicationActivities: [CustomActivity()])
activityController.excludedActivityTypes = [
UIActivity.ActivityType.assignToContact,
UIActivity.ActivityType.print,
UIActivity.ActivityType.addToReadingList,
UIActivity.ActivityType.saveToCameraRoll,
UIActivity.ActivityType.openInIBooks,
UIActivity.ActivityType.copyToPasteboard,
UIActivity.ActivityType.message,
UIActivity.ActivityType(rawValue: "com.apple.reminders.RemindersEditorExtension"),
UIActivity.ActivityType(rawValue: "com.apple.mobilenotes.SharingExtension"),
]
presentingVC.present(activityController, animated: true)
}
struct FileExtension {
static let value = ".\(Const.Ext)"
}
func loadFile(_ filename:String = "File") -> NSDictionary? {
let saveManager = SaveManager(SaveKey(filename,FileExtension.value))
if let openedData = saveManager.open(filename) {
return openedData
} else {
return nil
}
}
func loadImage(_ imageName:String) -> UIImage? {
var image: UIImage? = nil
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imageName)
image = UIImage(contentsOfFile: imageURL.path)
}
return image
}
func save(_ saveData:SaveData = [:],_ filename:String = "File"){
let saveManager = SaveManager(SaveKey(filename,FileExtension.value))
if !saveManager.save(saveData) {
print("Error Saving")
} else {
print("Saved Data")
}
}
func delete(_ saveData:SaveData = [:],_ filename:String = "File",_ needsExtension:Bool = true){
print("--\n[DELETING FILE]: \(filename)\n--")
let saveManager = SaveManager(SaveKey(filename, needsExtension ? FileExtension.value : ""))
if !saveManager.delete(filename) {
print("Error Saving")
} else {
print("Saved Data")
}
}
func retrieveFiles() -> [String] {
func listFilesFromDocumentsFolder() -> [String]? {
return try?FileManager.default.contentsOfDirectory(atPath:FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].path)
}
if let documentFiles = listFilesFromDocumentsFolder() {
return documentFiles.filter({ $0.contains(".\(Const.Ext)") })
} else {
return ["-"]
}
}
typealias SaveDataEncoded = String
protocol SaveDateEncodable {
func saveDataEncode() -> SaveDataEncoded
}
func createSaveDataWith(_ encodableData:[SaveDateEncodable]) -> SaveData {
var encodedSaveData = SaveDataEncoded()
for data in encodableData {
encodedSaveData.append(data.saveDataEncode())
}
return ["Data":encodedSaveData] as SaveData
}
typealias SaveData = NSDictionary
struct SaveKey {
let documentName: String
let fileExtension : String
var location : String {
return documentName + fileExtension
}
init(_ documentName : String = "Default",_ ext : String = ".plist") {
self.documentName = documentName
self.fileExtension = ext
}
}
struct SaveManager {
private var savekey : SaveKey
init(_ savekey : SaveKey) {
self.savekey = savekey
}
init() {
self.savekey = SaveKey()
}
}
extension SaveManager {
public var documentName : String {
return savekey.documentName
}
public var fileExtension : String {
return savekey.fileExtension
}
public var saveURL : URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(savekey.location)
}
}
extension SaveManager {
func save(_ data : NSDictionary) -> Bool {
let savedPlace = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(savekey.location)
return data.write(toFile: savedPlace.path, atomically: false)
}
func open(_ fileName : String) -> NSDictionary? {
let location = fileName
let savedPlace = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(location)
let data = NSDictionary(contentsOfFile: savedPlace.path)
return data
}
func delete(_ fileName : String) -> Bool {
let appendage = fileName + fileExtension
let url = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(appendage)
if !FileManager().fileExists(atPath: url.path) {
print("File: \(appendage) Does Not Exist")
}
else {
let url = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(appendage)
do {
try FileManager.default.removeItem(at: url)
print(" Deleted File: \(url) ")
} catch {
print("Failed to remove file \(appendage) ")
}
}
return true
}
}
//MARK: Data Saving - PLIST
struct DataPropertyKey {
static let documentName : String = "\(Const.Name)Data"
static let fileExtension : String = ".plist"
static let DocumentsDirectory : URL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent(documentName)
}
struct DataManager {
func getPath() -> String {
let documentName = DataPropertyKey.documentName
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let appendage = documentName + DataPropertyKey.fileExtension
let path = documentDirectory.appendingPathComponent(appendage)
return path
}
func makePlist(_ plistName : String, rootDictionary : NSDictionary) -> Bool {
var result = true
let documentName = plistName
let fileManager = FileManager.default
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let appendage = documentName + DataPropertyKey.fileExtension
let path = documentDirectory.appendingPathComponent(appendage)
if(!fileManager.fileExists(atPath: path)) {
let baseData = rootDictionary
let isWritten = baseData.write(toFile: path, atomically: true)
print("is the file created: \(isWritten)")
}
else {
result = false
}
return result
}
}
|
// AppContainerPresenterViewTableDelegate.swift
import Foundation
/// Presenter View Table Delegate
protocol AppContainerPresenterViewTableDelegate: ViewTableDelegate {
var interactor: AppContainerInteractor? { get set }
}
/// Presenter View Table Delegate Impl
struct AppContainerPresenterViewTableDelegateImpl: AppContainerPresenterViewTableDelegate {
var interactor: AppContainerInteractor?
func didSelectRowAt(_ indexPath: IndexPath) {
guard let allCellData = interactor?.allCellData else {
return
}
let detail = allCellData[indexPath.row].detail()
debugPrint(detail.description)
}
}
|
//
// CanvasCourseRouting.swift
// Nebula Messenger
//
// Created by Shelby McCowan on 1/9/19.
// Copyright © 2019 Shelby McCowan. All rights reserved.
//
import Foundation
import Alamofire
func getStudents(stringUrl: String){
print("HEY")
let requestJson = [String: Any]()
let url = URL(string: stringUrl)
do {
let _ = try JSONSerialization.data(withJSONObject: requestJson, options: [])
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("Bearer 7~3GQHD93XsKy9sVc6G0q1T0dHRngBb9625gU839g24tRnyMEYtQVyUIXZoRVSyW6S", forHTTPHeaderField: "Authorization")
Alamofire.request(request).responseJSON(completionHandler: { response -> Void in
print("READY")
switch response.result{
case .success(let Json):
print(Json)
let jsonObject = JSON(Json)
print(jsonObject)
case .failure(_):
print("CANVAS FAILED")
}
})
}catch{
print("what")
}
}
|
//
// Disney_Search_APIApp.swift
// Disney Search API
//
// Created by Student on 3/11/21.
//
import SwiftUI
@main
struct Disney_Search_APIApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
|
//
// MoreDefinitionsLabel.swift
// JISHO
//
// Created by Alex on 02/05/2020.
// Copyright © 2020 Alex McMillan. All rights reserved.
//
import Foundation
import UIKit
class MoreDefinitionsLabelView: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
selfInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
selfInit()
}
fileprivate func selfInit() {
font = .semiBold(size: 11)
}
func setText(forNumberOfItems n: Int) {
text = n == 0 ? nil : "and \(n) more"
}
}
|
//
// ViewController.swift
// Login
//
// Created by Stas Lavruk on 04.08.2018.
// Copyright © 2018 Stas Lavruk. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
/*
Login that the user entered.
*/
var userLoginText: String = ""
/*
A field that displays the login entered by the user.
*/
@IBOutlet weak var mainLogin: UILabel!
/*
In this method, two login fields and a password are filled in.
*/
override func viewDidLoad() {
super.viewDidLoad()
mainLogin.text = "Hello: " + userLoginText
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
struct Point {
let x: Int
let y: Int
}
protocol IMemento {
}
struct Parallelepiped {
private var x: Int
private var y: Int
private var width: Int
private var height: Int
init(x: Int, y: Int, width: Int, height: Int) {
self.x = x
self.y = y
self.width = width
self.height = height
}
mutating func move(_ point: Point) {
self.x += point.x
self.y += point.y
}
func save() -> IMemento {
return Memento(graphic: self)
}
mutating func restore(memento: IMemento) {
guard let momento = memento as? Memento else { return }
momento.restore(graphic: &self)
}
private struct Memento: IMemento {
private let x1y1: Point
private let x1y2: Point
private let x2y1: Point
private let x2y2: Point
init(graphic: Parallelepiped) {
self.x1y1 = Point(x: graphic.x, y: graphic.y)
self.x1y2 = Point(x: graphic.x, y: graphic.y + graphic.height)
self.x2y1 = Point(x: graphic.x + graphic.width, y: graphic.y)
self.x2y2 = Point(x: graphic.x + graphic.width, y: graphic.y + graphic.height)
}
func restore(graphic: inout Parallelepiped) {
graphic.x = x1y1.x
graphic.y = x1y1.y
graphic.width = x2y2.x - x1y1.x
graphic.height = x2y2.y - x2y1.y
}
}
}
var shots = [IMemento]()
var parallelepiped = Parallelepiped(x: 0, y: 0, width: 100, height: 100)
print(parallelepiped)
shots.append(parallelepiped.save())
parallelepiped.move(Point(x: 15, y: 10))
print(parallelepiped)
shots.append(parallelepiped.save())
parallelepiped.move(Point(x: 5, y: 10))
print(parallelepiped)
shots.append(parallelepiped.save())
parallelepiped.move(Point(x: 20, y: 30))
print(parallelepiped)
parallelepiped.restore(memento: shots[1])
print(parallelepiped)
|
//
// SlideBarStyle.swift
// SlideBar
//
import UIKit
// MARK: - Protocols
public protocol CommonSlideBarStyleProtocol {
var baseStyle: SlideBarStyleProtocol { set get }
var customStyle: SlideBarStyleProtocol? { set get }
}
public protocol SlideBarStyleProtocol {
// FONTS
var font: UIFont { set get }
var activeFont: UIFont { set get }
// COLOR PALETTE
var backgroundColor: UIColor { set get }
var fontColor: UIColor { set get }
var activeFontColor: UIColor { set get }
var indicatorColor: UIColor { set get }
var bgColor: UIColor { set get }
// FRAME VALUE ATTRIBUTES
var interItemSpacing: CGFloat { set get }
var arrangeByWidth: Bool { set get }
}
// MARK: - Structs
struct SlideBarStyleDefault: SlideBarStyleProtocol {
// FONTS
public var font: UIFont = .systemFont(ofSize: 14.0)
public var activeFont: UIFont = .boldSystemFont(ofSize: 14.0)
// COLOR PALETTE
public var backgroundColor: UIColor = .clear
public var fontColor: UIColor = .white
public var activeFontColor: UIColor = .white
public var indicatorColor: UIColor = .white
public var bgColor: UIColor = .clear
// FRAME VALUE ATTRIBUTES
public var interItemSpacing: CGFloat = 0.0
public var arrangeByWidth: Bool = true
public init() {}
}
public struct CommonSlideBarStyle: CommonSlideBarStyleProtocol {
public var baseStyle: SlideBarStyleProtocol = SlideBarStyleDefault()
public var customStyle: SlideBarStyleProtocol?
public init() {}
}
|
//
// Recipe.swift
// Final_Project
//
// Created by user181204 on 12/3/20.
//
import Foundation
import UIKit
struct Recipe: Codable {
let category: String
let title: String
let description: String
let ingredients: String
let directions: String
}
|
//
// SlideMenuTableViewCell.swift
// hecApp-iOS
//
// Created by Asianark on 16/2/26.
// Copyright © 2016年 Asianark. All rights reserved.
//
import UIKit
class SlideMenuTableViewCell: UITableViewCell {
@IBOutlet weak var item_icon: UIImageView!
@IBOutlet weak var item_title: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// ViewController.swift
// division
//
// Created by John Page on 29/01/2021.
// Copyright © 2021 John Page. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let calculatorBrain = CalculatorBrain()
let calculOnline = OnlineCalculatorBrain()
@IBOutlet weak var div1Textfield: UITextField!
@IBOutlet weak var div2Textfield: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func calculateButton(_ sender: Any) {
if div1Textfield.text != nil && div2Textfield.text != nil {
if let div1 = Int(div1Textfield.text!), let div2 = Int(div2Textfield.text!){
calculatorBrain.divideTwoNumbers(dividend: div1, divisor: div2) { (result, error) in
if error == nil, let result = result {
let resultAsString = NSString(format: "%.1f", result)
resultLabel.text = String(resultAsString)
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
//
// AppState+makeStore.swift
// RedCatWeather
//
// Created by Markus Pfeifer on 15.05.21.
//
import RedCat
extension AppState {
static func makeStore(configure: (Dependencies) -> AppState = configureDefaultState)
-> CombineStore<AppState, AppAction> {
Store(erasing: reducer,
environment: dependencies,
services: [CityRequestService(),
ForecastRequestService(),
AppEventService()],
configure: configure)
}
// for previews / debug
static func makeStore(configure: (inout AppState) -> Void) -> CombineStore<AppState, AppAction> {
makeStore {(env : Dependencies) in
var state = configureDefaultState(env)
configure(&state)
return state
}
}
// for previews / debug
static func configureDefaultState(_ env: Dependencies) -> AppState {
AppState(error: nil,
currentForecast: Forecast(city: "",
rawForecastType: .day,
requestState: .empty),
possibleCities: PossibleCities(prefix: "",
requestState: .empty),
currentMenu: .forecast)
}
static let dependencies = Dependencies {
Bind(\.debugDelay, to: .stoneage)
}
}
|
//
// GiphyAPI.swift
// Meow
//
// Created by Broccoli on 2017/6/29.
// Copyright © 2017年 broccoliii. All rights reserved.
//
import UIKit
import Moya
import ObjectMapper
import RxSwift
import SwiftyJSON
import RxMoya
let GiphyProvider = RxMoyaProvider<Giphy>()
public enum Giphy {
case search(query: String, limit: Int, offset: Int)
}
extension Giphy: TargetType {
public var headers: [String : String]? {
return nil
}
public var baseURL: URL {
return URL(string: "https://api.giphy.com/")!
}
public var path: String {
switch self {
case .search:
return "v1/gifs/search"
}
}
public var method: Moya.Method {
switch self {
case .search:
return .get
}
}
public var parameters: [String: Any]? {
switch self {
case .search(let query, let limit, let offset):
return ["api_key": "9dfbfbb0af284a4a8296e568dfd6f3f7",
"lang": "en",
"rating":"G",
"q":query,
"limit":limit,
"offset":offset]
}
}
public var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
public var task: Task {
switch self {
case .search:
return .requestPlain
}
}
public var sampleData: Data {
switch self {
case .search:
return Data()
}
}
}
extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
public func mapImageInfoArray() -> Single<[ImageInfo]> {
return flatMap { response -> Single<[ImageInfo]> in
let responseDataJSONArray = JSON(data: response.data)["data"]
var originalImageJSONArray = [Any?]()
for responseDataJSONObject in responseDataJSONArray.array! {
originalImageJSONArray.append(responseDataJSONObject["images"]["original"].object)
}
let objects = try! Mapper<ImageInfo>().mapArray(JSONObject: originalImageJSONArray) ?? [ImageInfo]()
return Single.just(objects)
}
}
}
//extension ObservableType where E == Response {
// public func mapImageInfoArray<T: BaseMappable>(_ type: T.Type) -> Observable<[T]> {
// return flatMap { response -> Observable<[T]> in
// return Observable.just(try response.mapImageInfoArray(T.self))
// }
// }
//}
|
//
// ClownViewController.swift
// NewMiniProject
//
// Created by Angela Huynh on 6/4/20.
// Copyright © 2020 Angela Huynh. All rights reserved.
//
import UIKit
class ClownViewController: UIViewController {
@IBAction func clownButton(_ sender: UIButton) {
let clownController = UIAlertController(title: "This is your writing prompt!", message: "You are secretly aware that your best friend is a super villain. Your best friend is secretly aware that you're a superhero. However neither of you know that the other knows.", preferredStyle: .alert); clownController.addAction (UIAlertAction(title: "Yay!", style: .default)); self.present(clownController, animated: true, completion:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the 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?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// Spotify.swift
// SpotifyManager
//
// Created by Paul Beffa on 13/09/2021.
//
import Foundation
import Combine
#if os(macOS)
import AppKit
#else
import UIKit
#endif
import SwiftUI
import KeychainAccess
import SpotifyWebAPI
/**
A helper class that wraps around an instance of `SpotifyAPI` and provides
convenience methods for authorizing your application.
Its most important role is to handle changes to the authorization information
and save them to persistent storage in the keychain.
*/
final class Spotify: ObservableObject {
private static let clientId: String = {
if let clientId = ProcessInfo.processInfo
.environment["CLIENT_ID"] {
return clientId
}
fatalError("Could not find 'CLIENT_ID' in environment variables")
}()
private static let clientSecret: String = {
if let clientSecret = ProcessInfo.processInfo
.environment["CLIENT_SECRET"] {
return clientSecret
}
fatalError("Could not find 'CLIENT_SECRET' in environment variables")
}()
/// The key in the keychain that is used to store the authorization
/// information: "authorizationManager".
let authorizationManagerKey = "authorizationManager"
/// The URL that Spotify will redirect to after the user either authorizes
/// or denies authorization for your application.
let loginCallbackURL = URL(
string: "spotify-manager://login-callback"
)!
/// A cryptographically-secure random string used to ensure than an incoming
/// redirect from Spotify was the result of a request made by this app, and
/// not an attacker. **This value is regenerated after each authorization**
/// **process completes.**
var authorizationState = String.randomURLSafe(length: 128)
/**
Whether or not the application has been authorized. If `true`, then you can
begin making requests to the Spotify web API using the `api` property of
this class, which contains an instance of `SpotifyAPI`.
When `false`, `LoginView` is presented, which prompts the user to login.
When this is set to `true`, `LoginView` is dismissed.
This property provides a convenient way for the user interface to be
updated based on whether the user has logged in with their Spotify account
yet. For example, you could use this property disable UI elements that
require the user to be logged in.
This property is updated by `authorizationManagerDidChange()`, which is
called every time the authorization information changes, and
`authorizationManagerDidDeauthorize()`, which is called every time
`SpotifyAPI.authorizationManager.deauthorize()` is called.
*/
@Published var isAuthorized = false
/// If `true`, then the app is retrieving access and refresh tokens. Used by
/// `LoginView` to present an activity indicator.
@Published var isRetrievingTokens = false
@Published var currentUser: SpotifyUser? = nil
/// The keychain to store the authorization information in.
let keychain = Keychain(service: "com.paulobef.SpotifyManager")
/// An instance of `SpotifyAPI` that you use to make requests to the Spotify
/// web API.
let api = SpotifyAPI(
authorizationManager: AuthorizationCodeFlowManager(
clientId: Spotify.clientId,
clientSecret: Spotify.clientSecret
)
)
var cancellables: Set<AnyCancellable> = []
// MARK: - Methods -
init() {
// Configure the loggers.
self.api.apiRequestLogger.logLevel = .trace
// self.api.logger.logLevel = .trace
// MARK: Important: Subscribe to `authorizationManagerDidChange` BEFORE
// MARK: retrieving `authorizationManager` from persistent storage
self.api.authorizationManagerDidChange
// We must receive on the main thread because we are updating the
// @Published `isAuthorized` property.
.receive(on: RunLoop.main)
.sink(receiveValue: authorizationManagerDidChange)
.store(in: &cancellables)
self.api.authorizationManagerDidDeauthorize
.receive(on: RunLoop.main)
.sink(receiveValue: authorizationManagerDidDeauthorize)
.store(in: &cancellables)
// MARK: Check to see if the authorization information is saved in
// MARK: the keychain.
if let authManagerData = keychain[data: self.authorizationManagerKey] {
do {
// Try to decode the data.
let authorizationManager = try JSONDecoder().decode(
AuthorizationCodeFlowManager.self,
from: authManagerData
)
print("found authorization information in keychain")
/*
This assignment causes `authorizationManagerDidChange` to emit
a signal, meaning that `authorizationManagerDidChange()` will
be called.
Note that if you had subscribed to
`authorizationManagerDidChange` after this line, then
`authorizationManagerDidChange()` would not have been called
and the @Published `isAuthorized` property would not have been
properly updated.
We do not need to update `isAuthorized` here because it is
already done in `authorizationManagerDidChange()`.
*/
self.api.authorizationManager = authorizationManager
} catch {
print("could not decode authorizationManager from data:\n\(error)")
}
}
else {
print("did NOT find authorization information in keychain")
}
}
/**
A convenience method that creates the authorization URL and opens it in the
browser.
You could also configure it to accept parameters for the authorization
scopes.
This is called when the user taps the "Log in with Spotify" button in
`LoginView`.
*/
func authorize() {
let url = api.authorizationManager.makeAuthorizationURL(
redirectURI: self.loginCallbackURL,
showDialog: true,
// This same value **MUST** be provided for the state parameter of
// `authorizationManager.requestAccessAndRefreshTokens(redirectURIWithQuery:state:)`.
// Otherwise, an error will be thrown.
state: authorizationState,
scopes: [
.userReadPlaybackState,
.userModifyPlaybackState,
.playlistModifyPrivate,
.playlistModifyPublic,
.userLibraryRead,
.userLibraryModify,
.userReadRecentlyPlayed
]
)!
// You can open the URL however you like. For example, you could open
// it in a web view instead of the browser.
// See https://developer.apple.com/documentation/webkit/wkwebview
#if os(macOS)
NSWorkspace.shared.open(url)
#else
UIApplication.shared.open(url)
#endif
}
/**
Saves changes to `api.authorizationManager` to the keychain.
This method is called every time the authorization information changes. For
example, when the access token gets automatically refreshed, (it expires
after an hour) this method will be called.
It will also be called after the access and refresh tokens are retrieved
using `requestAccessAndRefreshTokens(redirectURIWithQuery:state:)`.
Read the full documentation for
[SpotifyAPI.authorizationManagerDidChange][1].
[1]: https://peter-schorn.github.io/SpotifyAPI/Classes/SpotifyAPI.html#/s:13SpotifyWebAPI0aC0C29authorizationManagerDidChange7Combine18PassthroughSubjectCyyts5NeverOGvp
*/
func authorizationManagerDidChange() {
withAnimation(LoginView.animation) {
// Update the @Published `isAuthorized` property. When set to
// `true`, `LoginView` is dismissed, allowing the user to interact
// with the rest of the app.
self.isAuthorized = self.api.authorizationManager.isAuthorized()
}
print(
"Spotify.authorizationManagerDidChange: isAuthorized:",
self.isAuthorized
)
self.retrieveCurrentUser()
do {
// Encode the authorization information to data.
let authManagerData = try JSONEncoder().encode(
self.api.authorizationManager
)
// Save the data to the keychain.
keychain[data: self.authorizationManagerKey] = authManagerData
print("did save authorization manager to keychain")
} catch {
print(
"couldn't encode authorizationManager for storage " +
"in keychain:\n\(error)"
)
}
}
/**
Removes `api.authorizationManager` from the keychain and sets `currentUser`
to `nil`.
This method is called every time `api.authorizationManager.deauthorize` is
called.
*/
func authorizationManagerDidDeauthorize() {
withAnimation(LoginView.animation) {
self.isAuthorized = false
}
self.currentUser = nil
do {
/*
Remove the authorization information from the keychain.
If you don't do this, then the authorization information that you
just removed from memory by calling
`SpotifyAPI.authorizationManager.deauthorize()` will be retrieved
again from persistent storage after this app is quit and
relaunched.
*/
try keychain.remove(self.authorizationManagerKey)
print("did remove authorization manager from keychain")
} catch {
print(
"couldn't remove authorization manager " +
"from keychain: \(error)"
)
}
}
/**
Retrieve the current user.
- Parameter onlyIfNil: Only retrieve the user if `self.currentUser`
is `nil`.
*/
func retrieveCurrentUser(onlyIfNil: Bool = true) {
if onlyIfNil && self.currentUser != nil {
return
}
guard self.isAuthorized else { return }
self.api.currentUserProfile()
.receive(on: RunLoop.main)
.sink(
receiveCompletion: { completion in
if case .failure(let error) = completion {
print("couldn't retrieve current user: \(error)")
}
},
receiveValue: { user in
self.currentUser = user
}
)
.store(in: &cancellables)
}
}
|
//
// CupcakeRow.swift
// CupcakeCorner
//
// Created by Tino on 26/4/21.
//
import SwiftUI
struct CupcakeRow: View {
let cupcake: Cupcake
@EnvironmentObject var shoppingCart: ShoppingCart
var body: some View {
HStack {
Image(cupcake.name)
.resizable()
.scaledToFill()
.frame(width: 120, height: 120)
.clipped()
.cornerRadius(20)
.shadow(radius: 5)
VStack(alignment: .leading, spacing: 3) {
HStack {
Text(cupcake.name.capitalized)
Spacer()
Text("x \(cupcake.amount)")
}
.font(.title3)
Divider()
CheckBox("Sprinkes?", isOn: $shoppingCart.cupcakes[index].addSprinkles)
CheckBox("Extra frosting?", isOn: $shoppingCart.cupcakes[index].addExtraFrosting)
}
.padding(.trailing)
}
.padding()
}
var index: Int {
shoppingCart.cupcakes.firstIndex(where: { $0.name == cupcake.name })!
}
}
struct CupcakeRow_Previews: PreviewProvider {
static var previews: some View {
CupcakeRow(cupcake: Cupcake(name: "rainbow", amount: 2))
.environmentObject(ShoppingCart())
}
}
|
//
// DetalisViewController.swift
// CustomTableView
//
// Created by Nazim Uddin on 6/8/19.
// Copyright © 2019 Nazim Uddin. All rights reserved.
//
import UIKit
class DetalisViewController: UIViewController {
@IBOutlet weak var img: UIImageView!
@IBOutlet weak var lbl1: UILabel!
@IBOutlet weak var lbl2: UILabel!
var imgView:UIImage!
var lbl1Str:String!
var lbl2Str:String!
var singleData:AmazonModel!{
didSet{
imgView = singleData.img!
lbl1Str = singleData.title!
lbl2Str = singleData.details!
}
}
override func viewDidLoad() {
super.viewDidLoad()
img.image = imgView
lbl1.text = lbl1Str
lbl2.text = lbl2Str
// Do any additional setup after loading the view.
}
}
|
//
// CreateLabelPresenter.swift
// FundooApp
//
// Created by admin on 21/06/20.
// Copyright © 2020 admin. All rights reserved.
//
import Foundation
class LabelPresenter: LabelPresenterDelegate {
var labelView: LabelViewDelegate!
let dbManager = RemoteLabelManager.shared
init(delegate: LabelViewDelegate) {
self.labelView = delegate
}
func getLabels() {
DispatchQueue.main.async {
self.dbManager.getLabels(urlPath: RestUrl.GET_LABEL_LIST_URL_PATH) { [weak self] (labels) in
self?.labelView.updateLabelsDataSource(label: labels)
}
}
}
func deleteLabel(label:LabelResponse) {
dbManager.deleteLabel(label: label)
}
}
|
//
// Exam.swift
// com.moviles.psychoapp
//
// Created by macuser on 10/8/17.
// Copyright © 2017 Gustavo Adolfo Alegria Zu±iga. All rights reserved.
//
import UIKit
import Firebase
class Exam: NSObject {
var id: String!
var date: String?
var employer: String?
var maxScore: Double?
var name: String?
var score: Double?
var time: Double?
var testDescription: String?
var company: String?
var title: String?
var user: String?
var username: String?
var testList:[Test] = [Test]()
var ref: DatabaseReference!
override init(){
super.init()
}
convenience init(_ dict: Dictionary<String, AnyObject>) {
self.init()
// print(dict)
id = dict["id"] as! String!
date = dict["date"] as! String?
employer = dict["employer"] as! String?
maxScore = dict["maxScore"] as! Double?
name = dict["name"] as! String?
score = dict["score"] as! Double?
time = dict["time"] as! Double?
testDescription = dict["description"] as! String!
company = dict["company"] as! String?
title = dict["title"] as! String?
user = dict["user"] as! String?
username = dict["username"] as! String?
}
}
|
//
// TrendingTopicCollectionViewCell.swift
// Bracket
//
// Created by Justin Galang on 7/17/20.
// Copyright © 2020 Justin Galang. All rights reserved.
//
import UIKit
class TrendingCollectionViewCell: UICollectionViewCell {
@IBOutlet var tournamentTitle: UILabel!
@IBOutlet var tournamentImage: UIImageView!
static let identifier = "TrendingTopicCollectionViewCell"
static func nib() -> UINib {
return UINib(nibName: "TrendingTopicCollectionViewCell", bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
public func configure (with tournament: Tournament) {
self.tournamentTitle.text = tournament.title
// self.tournamentImage
}
}
|
//
// Hoge.swift
// protocol
//
// Created by 新井岩生 on 2018/04/24.
// Copyright © 2018年 新井岩生. All rights reserved.
//
import UIKit
// プロトコルを作る。
protocol Mochi {
func sayHello() -> String
}
class Hoge: NSObject {
// ここで、プロトコルに従うクラスのインスタンスを用意する。
var delegate: Mochi!
func say() -> String {
return delegate.sayHello()
}
}
|
//
// PopularModel.swift
// NYTimesPopular
//
// Created by Mostafa on 3/27/19.
// Copyright © 2019 Mostafa. All rights reserved.
//
import Foundation
struct Popular: Codable
{
let num_results: Int?
let results: [Result]?
init(results: [Result]) {
self.results = results
num_results = nil
}
}
struct Result: Codable
{
let url: String?
let adx_keywords: String?
let section: String?
let byline: String?
let type: String?
let title: String?
let abstract: String?
let published_date: String?
let source: String?
let id: Int?
let asset_id: Int?
let views: Int?
let uri: String?
let media: [Media]?
init(title: String, abstract: String, published_date: String)
{
self.title = title
self.abstract = abstract
self.published_date = published_date
(url, adx_keywords, section, byline, type, source, uri, id, asset_id, views, media) =
(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
}
var smallImage: String? {
get {
guard let media = self.media,
media.count > 0,
let mediaMetadata = media[0].mediaMetadata,
mediaMetadata.count > 0,
let imageURL = mediaMetadata[0].url
else { return nil }
return imageURL
}
}
var bigImage: String? {
get {
guard let media = self.media,
media.count > 0,
let mediaMetadata = media[0].mediaMetadata,
mediaMetadata.count > 2,
let imageURL = mediaMetadata[2].url
else { return nil }
return imageURL
}
}
}
struct Media: Codable
{
let type: String?
let subtype: String?
let caption: String?
let copyright: String?
let approvedForSyndication: Int?
let mediaMetadata: [Metadata]?
enum CodingKeys: String, CodingKey {
case type, subtype, caption, copyright
case approvedForSyndication = "approved_for_syndication"
case mediaMetadata = "media-metadata"
}
}
struct Metadata: Codable
{
let url: String?
let format: String?
let height: Int?
let width: Int?
}
|
//
// AccountListViewController.swift
// PasswordStorage
//
// Created by João Paulo dos Anjos on 01/02/18.
// Copyright © 2018 Joao Paulo Cavalcante dos Anjos. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class AccountListViewController: UIViewController {
// MARK: - Properties
@IBOutlet var emptyView: UIView!
@IBOutlet weak var tableView: UITableView!
private var viewModel = AccountListViewModel()
private let disposeBag = DisposeBag()
private let AccountTableViewCellIdentifier = "accountTableViewCellIdentifier"
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
bindElement()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.getAccounts()
}
// MARK: - IBActions
@IBAction func logoutButtonTouchUpInside(_ sender: UIBarButtonItem) {
self.showAlertWithOptions(title: "Logout", message: "", rightButtonTitle: "YES", leftButtonTitle: "NO", rightDissmisBlock: {
self.popToSignViewContoller()
}, leftDissmisBlock: { })
}
@IBAction func addButtonTouchUpInside(_ sender: UIBarButtonItem) {
self.navigationController?.pushViewController(AccountRegisterViewController.instantiate(), animated: true)
}
// MARK: - Services
// MARK: - MISC
func setupUI() {
}
// MARK: - Bind
func bindElement() {
viewModel.accounts.asObservable()
.bind(to: tableView.rx.items(cellIdentifier: AccountTableViewCellIdentifier,
cellType: AccountTableViewCell.self)) {
row, data, cell in
cell.setup(with: data)
}.disposed(by: disposeBag)
tableView.rx.modelSelected(Account.self)
.subscribe(onNext: { data in
self.showDetailsViewContoller(account: data)
}).disposed(by: disposeBag)
tableView.rx.setDelegate(self)
.disposed(by: disposeBag)
}
// MARK - Navigation
func showDetailsViewContoller(account: Account) {
let controller = AccountDetailViewController.instantiate()
controller.account = account
self.navigationController?.pushViewController(controller, animated: true)
}
func popToSignViewContoller() {
self.navigationController?.dismiss(animated: true, completion: nil)
AutoLoginConvience().clear()
}
}
extension AccountListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
}
extension AccountListViewController {
// MARK: - Instantiation
static func instantiate() -> AccountListViewController {
let storyboard = UIStoryboard(name: "Account", bundle: nil)
return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! AccountListViewController
}
}
|
// Playground - noun: a place where people can play
import UIKit
/*:
The set [1,2,3,⋯,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive.
*/
/*:
1,2,3,4
1,2,4,3
1,3,2,4
1,3,4,2
1,4,2,3
1,4,3,2
1, 2, 6, 24...
1,4,3,2
0,3,2,1 -> 0*6+3*2+1
sort digits,
n=4, k=6
nn = [1,2,3,4]
m = [1,2,6,24]
k1 = k
a1 = k(nFact[n-1])
k2 = k%(nFact[n-1])
a2 = k2/(nFact[n-2])
...
3, 6
nn = [1,2,3]
nFact = [1,1,2,6]
k1 = 6
a1 = 6/2 = 3
k2 = 6%2 = 0
a2 = 0/1 = 0
ak = 0%1 = 0
*/
func kthPermutationSequence(n:Int, k:Int) -> [Int] {
var nFact = [1]
for index in 1...n {
nFact.append(index*(nFact[index-1]))
}
nFact
var m = [Int]()
for index in 1...n {
m.append(index)
}
m
var sequence = [Int]()
var d = k
for var i=n-1; i>0; i-- {
var f = nFact[i+1]
var a = d/f
println("m before: \(m), a: \(a), d: \(d), nfact: \(f)")
sequence.append(m[a])
m.removeAtIndex(a)
println("m after: \(m)")
d = d%(f)
}
sequence.append(m.first!)
return sequence
}
kthPermutationSequence(3, 6 |
//
// DataTemp.swift
// ShoppingList
//
// Created by leslie on 2/24/20.
// Copyright © 2020 leslie. All rights reserved.
//
import Foundation
enum ViewMode {
case Simple
case Food
}
var currentViewModeValue: ViewMode = .Simple
var indexLetters: [String] = ["#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
var categories: [String] = ["B", "C", "D", "G", "J", "L", "M", "O", "P", "T", "Y"]
var items1D: [String] = ["Lettuce", "Tomatoes", "Milk", "Granola", "Donuts", "Cookies", "Butter", "Cheese", "Lemonade", "Yogurt", "Oatmeal", "Juice", "Tea", "Coffee", "Bagels", "Brownies", "Potatoes", "Onions"]
var items2D: [[String]] = [["Bagels", "Brownies", "Butter"], ["Cheese", "Coffee", "Cookies"], ["Donuts"], ["Granola"], ["Juice"], ["Lemonade", "Lettuce"], ["Milk"], ["Oatmeal", "Onions"], ["Potatoes"], ["Tea", "Tomatoes"], ["Yogurt"]]
var descriptions: [String] = ["1 lb.", "Sweet tomatoes", "2 lts.", "12 bars", "A dozen", "Oreos", "2", "Lactose free", "2 lts.", "Strawberrie yogurt", "1 box", "Orange juice", "Green tea", "1 bag of beans", "6", "Chocolate brownies", "2 lbs.", "1 lb."]
var images1D: [String] = ["lettuce", "tomato", "milk", "granola", "donuts", "cookies", "butter", "cheese", "lemonade", "yogurt", "oatmeal", "juice", "tea", "coffee", "bagels", "brownies", "potato", "onions"]
var images2D: [String: String] = ["Lettuce": "lettuce", "Tomatoes": "tomato", "Milk": "milk", "Granola": "granola", "Donuts": "donuts", "Cookies": "cookies", "Butter": "butter", "Cheese": "cheese", "Lemonade": "lemonade", "Yogurt": "yogurt", "Oatmeal": "oatmeal", "Juice": "juice", "Tea": "tea", "Coffee": "coffee", "Bagels": "bagels", "Brownies": "brownies", "Potatoes": "potato", "Onions": "onions"]
var selected: [Bool] = [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true]
|
//
// SegmentedViewController.swift
// Liftoff
//
// Created by Pavol Margitfalvi on 19/12/2018.
// Copyright © 2018 Pavol Margitfalvi. All rights reserved.
//
import UIKit
class SegmentedViewController: UIViewController {
@IBOutlet weak var blurViewHeight: NSLayoutConstraint!
weak var dataSource: SegmentedDataSource?
weak var delegate: SegmentedDelegate?
var tapRecognizer: UITapGestureRecognizer!
///////////////////////////////
// Only for testing purposes//
//////////////////////////////
var longPressRecognizer: UILongPressGestureRecognizer!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let childvc = self as? MissionViewController {
childvc.viewWillAppear(animated)
} else if let childvc = self as? RocketViewController {
childvc.viewWillAppear(animated)
} else if let childvc = self as? LocationViewController {
childvc.viewWillAppear(animated)
}
}
override func viewDidLoad() {
super.viewDidLoad()
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapRecognized(sender: )))
view.addGestureRecognizer(tapRecognizer)
tapRecognizer.isEnabled = false
}
@objc func tapRecognized(sender: UITapGestureRecognizer) {
guard let contentView = view.viewWithTag(255) else { return }
if !contentView.frame.contains(sender.location(in: contentView)) {
delegate?.readyToDismiss()
tapRecognizer.isEnabled = false
}
}
}
|
//
// detailscontroller.swift
// remoteios
//
// Created by Hasanul Isyraf on 04/07/2017.
// Copyright © 2017 Hasanul Isyraf. All rights reserved.
//
import UIKit
class detailscontroller: UIViewController,UITableViewDelegate,UITableViewDataSource,UIPopoverPresentationControllerDelegate {
@IBOutlet weak var menudetailview: UITableView!
@IBOutlet weak var tableview: UITableView!
var detailstt:[String]? = []
var activitiyindicator:UIActivityIndicatorView = UIActivityIndicatorView()
var menumanager4 = menumanager()
var stringPassed = ""
var ttinfo = listttobject()
var servicenumberstr:String?
var correctpairstr:String?
var targetcabinetstr:String?
var targetdsloutstr:String?
var targetpotsoutstr:String?
var speedstr:String?
var loginidstr:String?
var addressstr:String?
var menushowing = false
let arraydatasources = ["History","Maps"]
@IBOutlet weak var leadingconstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
//hide the menu when first loading
leadingconstraint.constant = -140
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
activitiyindicator.center = self.view.center
activitiyindicator.hidesWhenStopped = true
activitiyindicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activitiyindicator)
activitiyindicator.startAnimating()
fetchsummary()
// Do any additional setup after loading the view.
}
func fetchsummary(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/details_tt_mobile.php?ttno="+stringPassed)!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
self.detailstt = [String]()
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
if let summaryfromjson = json["masterlist"] as? [[String:AnyObject]]{
for summaryfromjson in summaryfromjson {
_ = detailsttobject()
if let servicenumber = summaryfromjson["SERVICE NUMBER"] as? String, let cabinetid = summaryfromjson["TARGET CABINET"], let correctpair = summaryfromjson["CORRECT DSIDE PAIR"], let targetpotsout = summaryfromjson["TARGET POTS OUT"], let speed = summaryfromjson["SPEED"], let targetdslout = summaryfromjson["TARGET DSL OUT"]{
self.servicenumberstr = servicenumber
self.correctpairstr = correctpair as? String
self.targetpotsoutstr = targetpotsout as? String
self.targetdsloutstr = targetdslout as? String
self.targetcabinetstr = cabinetid as? String
self.speedstr = speed as? String
self.detailstt?.append(self.stringPassed)
self.detailstt?.append("Servicenumber:"+servicenumber)
self.detailstt?.append("Correct Pair:"+(correctpair as? String)!)
self.detailstt?.append("Target Pots Out:"+(targetpotsout as?String)!)
self.detailstt?.append("Target DSL Out:"+(targetdslout as? String)!)
self.detailstt?.append("Cabinet ID:"+(cabinetid as? String)!)
self.detailstt?.append("Speed:"+(speed as? String)!)
// listttobjects.ttno = ttno
// listttobjects.servicenumber = servicenumber
// listttobjects.referencenumber = referencenumber as? String
// listttobjects.cabinetid = cabinetid as? String
// listttobjects.contactnumber = customer_mobile_no as? String
// listttobjects.priority = priority as? String
// listttobjects.remark = remark as? String
// listttobjects.symtomcode = symtomcode as? String
// listttobjects.customername = customer_name as? String
// listttobjects.eside = esdie as? String
// listttobjects.dside = dsdie as? String
// listttobjects.createddate = createddate as? String
// listttobjects.reasoncode = reasoncode as? String
// print(listttobjects.cabinetid!)
}
}
}
if let summaryfromjson2 = json["tt_info"] as? [[String:AnyObject]]{
for summaryfromjson2 in summaryfromjson2 {
if let loginid = summaryfromjson2["referencenumber"] as? String{
self.loginidstr = loginid
self.detailstt?.append("Login ID:"+loginid)
}
}
}
if let address = json["address"] as? String{
self.addressstr = address.trimmingCharacters(in: .whitespacesAndNewlines)
self.detailstt?.append("Address:"+address)
}
DispatchQueue.main.async {
self.tableview.reloadData()
self.activitiyindicator.stopAnimating()
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell1:UITableViewCell?
if(tableView == self.tableview){
let cell = tableView.dequeueReusableCell(withIdentifier: "detailcell", for: indexPath) as! detailscell
cell.itemdetails.text = self.detailstt![indexPath.item]
cell1 = cell
}
if(tableView == self.menudetailview){
let cell = tableView.dequeueReusableCell(withIdentifier: "menucelldetail", for: indexPath) as! viewcellmenudetail
cell.itemdetails.text = self.arraydatasources[indexPath.item]
cell1 = cell
}
return cell1!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int = 0
if(tableView == self.tableview){
count = self.detailstt?.count ?? 0
}
if(tableView == self.menudetailview){
count = self.arraydatasources.count
}
return count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(tableView == self.tableview){
let updatevie = UIStoryboard(name:"userupdating",bundle:nil).instantiateViewController(withIdentifier: "updatestatus") as! updatestatusview
updatevie.ttinfo = ttinfo
navigationController?.pushViewController(updatevie, animated: true)
let index = navigationController?.viewControllers.index(of: self)
navigationController?.viewControllers.remove(at: index!)
}
if(tableView == self.menudetailview){
let textselected = arraydatasources[indexPath.item]
if(textselected == "History"){
//open the popover modal
self.performSegue(withIdentifier: "poplisttt", sender: self)
}
if(textselected == "Maps"){
let updatevie = UIStoryboard(name:"maps",bundle:nil).instantiateViewController(withIdentifier: "mapview") as! mapsviews
navigationController?.pushViewController(updatevie, animated: true)
}
}
}
//for popover modal history of every tt
@IBAction func openmenu4(_ sender: Any) {
if(menushowing){
leadingconstraint.constant = -140
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
else{
leadingconstraint.constant = 0
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
menushowing = !menushowing
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "poplisttt"{
let popoverViewController = segue.destination as! popoverlistttViewController
popoverViewController.ttno = stringPassed
popoverViewController.popoverPresentationController?.delegate = self
}
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
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.
}
*/
}
|
import Corvus
import Fluent
import Foundation
final class Account: CorvusModel {
static let schema = "accounts"
@ID
var id: UUID? {
didSet {
if id != nil {
$id.exists = true
}
}
}
@Field(key: "name")
var name: String
@Children(for: \.$account)
var transactions: [Transaction]
@Parent(key: "user_id")
var user: CorvusUser
@Timestamp(key: "deleted_at", on: .delete)
var deletedAt: Date?
init(id: UUID? = nil, name: String) {
self.id = id
self.name = name
}
init() {}
}
struct CreateAccount: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
return database.schema(Account.schema)
.id()
.field("name", .string, .required)
.field("deleted_at", .date)
.field(
"user_id",
.uuid,
.references(CorvusUser.schema, .id, onDelete: .cascade)
)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema(Account.schema).delete()
}
}
extension Account: Equatable {
static func == (lhs: Account, rhs: Account) -> Bool {
var result = lhs.name == rhs.name
if let lhsId = lhs.id, let rhsId = rhs.id {
result = result && lhsId == rhsId
}
return result
}
}
|
//
// PickedView.swift
// My Restaurants
//
// Created by 苏菲 on 2017-03-29.
// Copyright © 2017 Sophie. All rights reserved.
//
import UIKit
import EasyPeasy
import CoreData
import SVProgressHUD
class PickedView: UIView {
let background = UIVisualEffectView(effect: UIBlurEffect(style: .light))
let canvas = UIView()
let imageView = UIImageView()
let nameLabel = UILabel()
let statusLabel = UILabel()
let addressLabel = UILabel()
let tagLabel = UILabel()
let refreshButton = UIButton()
let mapButton = UIButton()
let cancelButton = UIButton()
var restaurant: NSManagedObject?{
didSet{
addView()
}
}
weak var controller: RestaurantPickingViewController?
weak var mainController: ViewController?
override init(frame: CGRect){
super.init(frame: frame)
self.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
}
func addView(){
let height = UIScreen.main.bounds.height
self.addSubview(background)
background.frame = self.frame
background.addSubview(canvas)
canvas.backgroundColor = .white
canvas.translatesAutoresizingMaskIntoConstraints = false
canvas <- [CenterX(), Top(height/5.5 - 50), Left(50), Right(50), Height(>=0)]
canvas.layer.cornerRadius = 10
// canvas.layer.masksToBounds = true
canvas.layer.shadowColor = UIColor.black.cgColor
canvas.layer.shadowOpacity = 0.5
canvas.layer.shadowOffset = CGSize(width: 0, height: 5)
canvas.layer.shadowRadius = 10
canvas.addSubview(imageView)
if let imageData = restaurant?.value(forKey: "image") as? Data{
let image = UIImage(data: imageData)
imageView.image = image
}
else{
imageView.image = #imageLiteral(resourceName: "free")
}
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 5
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView <- [Left(8), Right(8), Top(10), Height(height/4)]
canvas.addSubview(nameLabel)
if let name = restaurant?.value(forKey: "name") as? String{
nameLabel.text = name
} else{
nameLabel.text = "Name Of Restaurant"
}
nameLabel.textColor = .black
nameLabel.numberOfLines = 0
nameLabel.lineBreakMode = .byWordWrapping
nameLabel.font = UIFont.systemFont(ofSize: 22, weight: UIFontWeightUltraLight)
nameLabel.sizeToFit()
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel <- [Top(15).to(imageView, .bottom), Left().to(imageView, .left), Right(10), Height(>=0)]
canvas.addSubview(statusLabel)
//statusLabel.text = "Open Now"
statusLabel.textColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)
statusLabel.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular)
statusLabel.sizeToFit()
statusLabel.translatesAutoresizingMaskIntoConstraints = false
statusLabel <- [Left().to(imageView, .left), Top(5).to(nameLabel, .bottom)]
canvas.addSubview(addressLabel)
if let address = restaurant?.value(forKey: "location") as? String{
addressLabel.text = address
} else{
addressLabel.text = "Address Of Restaurant"
}
addressLabel.numberOfLines = 0
addressLabel.lineBreakMode = .byWordWrapping
addressLabel.textColor = .darkGray
addressLabel.font = UIFont.systemFont(ofSize: 17, weight: UIFontWeightLight)
addressLabel.sizeToFit()
addressLabel.translatesAutoresizingMaskIntoConstraints = false
addressLabel <- [Left().to(imageView, .left), Top(10).to(statusLabel, .bottom), Right().to(imageView, .right), Height(>=0)]
canvas.addSubview(tagLabel)
var classicTags = [String]()
var customTags = [String]()
if let tags = restaurant?.value(forKey: "classicTags") as? [String]{
classicTags = tags
}
if let cusTags = restaurant?.value(forKey: "customTags") as? [String]{
customTags = cusTags
}
tagLabel.text = (classicTags + customTags).joined(separator: ", ")
tagLabel.numberOfLines = 0
tagLabel.lineBreakMode = .byWordWrapping
tagLabel.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightLight)
tagLabel.textColor = UIColor.gray
tagLabel.translatesAutoresizingMaskIntoConstraints = false
tagLabel <- [Left().to(imageView, .left), Top(5).to(addressLabel, .bottom), Right().to(imageView, .right), Height(>=0)]
let buttonSpace = (UIScreen.main.bounds.width - 100 - 3*30)/4
canvas.addSubview(refreshButton)
refreshButton.setImage(#imageLiteral(resourceName: "refresh"), for: .normal)
refreshButton.addTarget(self, action: #selector(refresh), for: .touchUpInside)
refreshButton.translatesAutoresizingMaskIntoConstraints = false
refreshButton <- [Left(buttonSpace), Top(50).to(tagLabel, .bottom), Height(30), Width(30), Bottom(20)]
canvas.addSubview(mapButton)
mapButton.setImage(#imageLiteral(resourceName: "map"), for: .normal)
mapButton.addTarget(self, action: #selector(showOnMap), for: .touchUpInside)
mapButton.translatesAutoresizingMaskIntoConstraints = false
mapButton <- [CenterX(), Top().to(refreshButton, .top), Height(30), Width(30), Bottom(20)]
canvas.addSubview(cancelButton)
cancelButton.setImage(#imageLiteral(resourceName: "cancel"), for: .normal)
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
cancelButton <- [Right(buttonSpace), Top().to(refreshButton, .top), Height(30), Width(30), Bottom(20)]
}
func cancel(){
self.isHidden = true
}
func refresh(){
controller?.pickingView.buttonTapped()
}
func showOnMap(){
SVProgressHUD.show()
SVProgressHUD.setDefaultMaskType(.black)
let location = restaurant?.value(forKey:"location") as! String
if let placeId = restaurant?.value(forKey: "placeId") as? String {
self.mainController?.showRestaurantOnMap(placeId: placeId, location: "")
} else{
self.mainController?.showRestaurantOnMap(placeId: "", location: location)
}
_ = controller?.navigationController?.popViewController(animated: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// TableViewCell.swift
// SaneScanner
//
// Created by Stanislas Chevallier on 09/05/2021.
// Copyright © 2021 Syan. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.isCatalyst {
backgroundColor = .clear
}
}
}
|
//
// ArticleViewModel.swift
// develop_head
//
// Created by zhj on 2019/6/14.
// Copyright © 2019年 zhj. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import RxDataSources
class ArticleViewModel{
private var page:Int = 1
var data = BehaviorSubject<[SectionModel<String,Article>]>(value:[])
var reload = PublishSubject<Bool>()
var callback:Callback<Bool>?
var articleModel:ArticleModel?
func requestLatest() {
// let group = DispatchGroup()
// group.enter()
// group.enter()
// group.enter()
ApiProvider.request(.dailies("latest"), model:ArticleModel.self) {
self.articleModel = $0
self.data.onNext([SectionModel(model:"1",items:self.articleModel!.article!)])
self.reload.onNext(true)
}
}
func requestPreDate() {
ApiProvider.request(.dailies(articleModel!.preDate!), model:ArticleModel.self) {
let old = self.articleModel!.article
self.articleModel?.article = old! + $0!.article!
self.data.onNext([SectionModel(model:"1",items:self.articleModel!.article!)])
self.reload.onNext(false)
}
}
func requestByNode(_ node:Int, more:Bool) {
ApiProvider.request(.by_node(node,page:page), model:[Article].self) {
self.page += 1
if more{
let old = self.articleModel!.article
self.articleModel?.article = old! + $0!
}else{
self.articleModel = ArticleModel()
self.articleModel?.article = $0
}
self.callback?(!more)
}
}
}
|
//
// MeasureLeafViewController.swift
// florafinder
//
// Created by Andrew Tokeley on 17/03/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import Foundation
import UIKit
import PureLayout
enum MeasureScale
{
case OneToOne
case PhoneScale
}
class MeasureLeafViewController: UIViewController
{
//MARK: - Constants
let PADDING:CGFloat = 20
let PADDING_SMALL:CGFloat = 4
let SLIDER_WIDTH:CGFloat = 40
let TOOLBAR_HEIGHT:CGFloat = 64
let TOP_NAV_HEIGHT:CGFloat = 64
let SCALE_TITLE = "Scale"
let SCALE_ONETOONE = "Small leaves"
let SCALE_PHONE = "Large leaves"
let CANCEL = "Cancel"
let DONT_SET = "Clear"
let TITLE_DEFAULT = "Measure"
let DONE_BUTTON = "Done"
let HORIZONTAL_SLIDER = 0
let VERTICAL_SLIDER = 1
var measureRegion: CGRect!
var initialWidthInCM: CGFloat = 0
var initialHeightInCM: CGFloat = 0
//MARK: - Initialisers
internal override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(widthCM: CGFloat, heightCM: CGFloat, delegate: MeasureLeafDelegate)
{
self.init(nibName: nil, bundle: nil)
self.delegate = delegate
self.initialWidthInCM = widthCM
self.initialHeightInCM = heightCM
}
//MARK: - UIViewController overrides
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLoad() {
self.title = self.TITLE_DEFAULT
// Define the region used to take measurements
self.measureRegion = CGRectMake(PADDING, TOP_NAV_HEIGHT + PADDING, UIScreen.mainScreen().bounds.size.width - 2 * PADDING, UIScreen.mainScreen().bounds.size.height - (2 * PADDING + TOOLBAR_HEIGHT + TOP_NAV_HEIGHT))
let containerView = UIView(frame: UIScreen.mainScreen().bounds)
containerView.backgroundColor = UIColor.whiteColor()
containerView.addSubview(sizeIndicator)
containerView.addSubview(toolbar)
containerView.addSubview(phoneGrid)
containerView.addSubview(grid)
containerView.addSubview(resizeHandle)
self.navigationItem.rightBarButtonItem = self.setButton
self.view = containerView;
// work out which scale will contain this dimension
if initialWidthInCM <= maxWidthInCentimetres(MeasureScale.OneToOne) && initialHeightInCM <= maxHeightInCentimetres(MeasureScale.OneToOne)
{
scale = MeasureScale.OneToOne
}
else if initialWidthInCM <= maxWidthInCentimetres(MeasureScale.PhoneScale) && initialHeightInCM <= maxHeightInCentimetres(MeasureScale.PhoneScale)
{
scale = MeasureScale.PhoneScale
}
else
{
// ABORT!
}
moveResizeHandleTo(initialWidthInCM, heightCM: initialHeightInCM)
}
override func loadView() {
}
override func viewDidAppear(animated: Bool) {
}
override func viewWillAppear(animated: Bool) {
self.view.needsUpdateConstraints()
}
override func updateViewConstraints() {
toolbar.autoPinEdgeToSuperviewEdge(ALEdge.Leading)
toolbar.autoPinEdgeToSuperviewEdge(ALEdge.Trailing)
toolbar.autoPinEdgeToSuperviewEdge(ALEdge.Bottom)
toolbar.autoSetDimension(ALDimension.Height, toSize: TOOLBAR_HEIGHT)
// centre grids with fixed width and heights - makes it easier for scaling if we know these dimensions
phoneGrid.autoCenterInSuperview()
phoneGrid.autoSetDimension(ALDimension.Width, toSize: self.measureRegion.width)
phoneGrid.autoSetDimension(ALDimension.Height, toSize: self.measureRegion.height)
grid.autoCenterInSuperview()
grid.autoSetDimension(ALDimension.Width, toSize: self.measureRegion.width)
grid.autoSetDimension(ALDimension.Height, toSize: self.measureRegion.height)
super.updateViewConstraints()
}
//MARK: - Properties
var delegate: MeasureLeafDelegate!
var firstUpdateViewConstraints = true
var scaleFactor: CGFloat
{
// return the scale factor for the current scale
return scaleFactor(scale)
}
/**
Return the scale factor for the given measure scale
*/
func scaleFactor(scale: MeasureScale) -> CGFloat
{
switch scale
{
case .OneToOne:
return 1
case .PhoneScale:
let phoneWidth = Units.centimetresToPoints(Units.sizeOfPhoneInCentimetres.width)
let phoneViewWidth:CGFloat = phoneGrid.phoneRectSize.width
return CGFloat(phoneWidth)/phoneViewWidth
}
}
var widthInCentimetres: CGFloat
{
return self.sizeIndicator.frame.size.width/Units.centimetresToPoints(1.0) * scaleFactor
}
var heightInCentimetres: CGFloat
{
return self.sizeIndicator.frame.size.height/Units.centimetresToPoints(1.0) * scaleFactor
}
var scale: MeasureScale = MeasureScale.OneToOne
{
didSet
{
phoneGrid.alpha = scale == .OneToOne ? 0 : 1
grid.alpha = scale == .OneToOne ? 1 : 0
}
}
lazy var sizeIndicator: UIView = {
let view = UIView()
view.backgroundColor = UIColor.leafLightGreen()
view.alpha = 0.5
return view
}()
lazy var resizeHandle: UIView = {
let containerView = UIView(frame: CGRect(x: 100, y: 100, width: 80, height: 80))
containerView.userInteractionEnabled = true
let view = UIView(frame: CGRect(x: 35, y: 35, width: 10, height: 10))
view.backgroundColor = UIColor.leafDarkGreen()
containerView.addSubview(view)
let drag = UIPanGestureRecognizer(target: self, action: #selector(MeasureLeafViewController.handleDrag(_:)))
containerView.addGestureRecognizer(drag)
return containerView
}()
lazy var setButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: self.DONE_BUTTON, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(MeasureLeafViewController.handleSetButtonClick(_:)))
return button
}()
lazy var toolbar: UIToolbar = {
let toolbar = UIToolbar()
let spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let dontSpecify = UIBarButtonItem(title: self.DONT_SET, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(MeasureLeafViewController.handleDontSpecifyButtonClick(_:)))
toolbar.items = [self.scaleButton, spacer, dontSpecify]
return toolbar
}()
lazy var scaleButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: self.SCALE_TITLE, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(MeasureLeafViewController.handleScaleButtonClick(_:)))
return button
}()
lazy var phoneGrid: IPhoneGrid = {
let grid = IPhoneGrid(frame: self.measureRegion, rows: 3, columns: 4)
grid.userInteractionEnabled = false
// always hidden initially
grid.alpha = 0
return grid
}()
lazy var grid: UIView = {
let grid = Grid(frame: self.measureRegion, gridSizeInCM: 1.0)
grid.userInteractionEnabled = false
return grid
}()
lazy var actions: UIAlertController = {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: self.SCALE_ONETOONE, style: UIAlertActionStyle.Default, handler:self.handleScaleAction))
actionSheet.addAction(UIAlertAction(title: self.SCALE_PHONE, style: UIAlertActionStyle.Default, handler:self.handleScaleAction))
actionSheet.addAction(UIAlertAction(title: self.CANCEL, style: UIAlertActionStyle.Cancel, handler:self.handleScaleAction))
return actionSheet
}()
//MARK: - Actions
func handleDrag(recognizer: UIPanGestureRecognizer)
{
let translation = recognizer.translationInView(self.view)
if let view = recognizer.view
{
let newCentre = CGPointMake(view.center.x + translation.x, view.center.y + translation.y)
if (measureRegion.contains(newCentre))
{
moveResizeHandleTo(newCentre)
recognizer.setTranslation(CGPointMake(0, 0), inView:self.view)
}
}
}
func handleSetButtonClick(sender: UIBarButtonItem)
{
self.delegate.measureCompleted(self.widthInCentimetres, length: self.heightInCentimetres)
self.navigationController?.popViewControllerAnimated(true)
}
func handleDontSpecifyButtonClick(sender: UIBarButtonItem)
{
self.delegate.measureNotDefined()
self.navigationController?.popViewControllerAnimated(true)
}
func handleScaleButtonClick(sender: UIBarButtonItem)
{
self.presentViewController(actions, animated: true, completion: nil)
}
func handleScaleAction(action: UIAlertAction)
{
if action.title == SCALE_ONETOONE
{
scale = .OneToOne
}
else if action.title == SCALE_PHONE
{
scale = .PhoneScale
}
else if action.title == CANCEL
{
return
}
// use this scaleFactor to toggle between 1:1 and phone scale
let s = scaleFactor(MeasureScale.PhoneScale)
if (scale == .OneToOne)
{
let deltaX = sizeIndicator.frame.size.width * (s - 1)
let newX = resizeHandle.center.x + deltaX
let deltaY = sizeIndicator.frame.size.height * (s - 1)
let newY = resizeHandle.center.y - deltaY
moveResizeHandleTo(newX, screenY: newY)
}
else if (scale == .PhoneScale)
{
// reduce th
let deltaX = sizeIndicator.frame.size.width * ( 1 - 1/s)
let newX = resizeHandle.center.x - deltaX
let deltaY = sizeIndicator.frame.size.height * ( 1 - 1/s)
let newY = resizeHandle.center.y + deltaY
moveResizeHandleTo(newX, screenY: newY)
}
}
//MARK: - Functions
func maxHeightInCentimetres(scale: MeasureScale) -> CGFloat
{
let scaleFactor = self.scaleFactor(scale)
return Units.pointsToCentimetre(self.measureRegion.height) * scaleFactor
}
func maxWidthInCentimetres(scale: MeasureScale) -> CGFloat
{
let scaleFactor = self.scaleFactor(scale)
return Units.pointsToCentimetre(self.measureRegion.width) * scaleFactor
}
func moveResizeHandleTo(screenX: CGFloat, screenY: CGFloat)
{
let maxX = measureRegion.origin.x + measureRegion.size.width
let minY = measureRegion.origin.y
let x = screenX > maxX ? maxX : screenX
let y = screenY < minY ? minY : screenY
resizeHandle.center = CGPointMake(x, y)
setSizeIndicatorFrame()
}
func moveResizeHandleTo(centre: CGPoint)
{
moveResizeHandleTo(centre.x, screenY: centre.y)
}
func moveResizeHandleTo(widthCM: CGFloat, heightCM: CGFloat)
{
// convert cms into screen coordinates)
let x = Units.centimetresToPoints(widthCM)/self.scaleFactor + PADDING
let y = self.view.frame.size.height - (Units.centimetresToPoints(heightCM)/self.scaleFactor + TOOLBAR_HEIGHT + PADDING)
moveResizeHandleTo(x, screenY: y)
}
func updateTitle()
{
self.title = String(format: "%.1f x %.1f cm", self.widthInCentimetres, self.heightInCentimetres)
}
func setSizeIndicatorFrame()
{
// size indicator is bound to the position of the resizeHandle
let x = PADDING
let y = resizeHandle.center.y
let width = (resizeHandle.center.x - PADDING)
let height = (self.view.frame.size.height - (y + TOOLBAR_HEIGHT + PADDING))
self.sizeIndicator.frame.origin = CGPoint(x: x, y: y)
self.sizeIndicator.frame.size = CGSize(width: width, height: height)
self.updateTitle()
}
} |
//
// MoviesTableViewController.swift
// Movies
//
// Created by Rodrigo Morbach on 04/11/18.
// Copyright © 2018 Movile. All rights reserved.
//
import UIKit
import CoreData
class MoviesTableViewController: UITableViewController {
var selectedMovie: Movie?
var moviesDataProvider: MoviesCoreDataProvider?
var movies = [Movie]()
@IBOutlet var emptyDataView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
//self.navigationController?.navigationBar.barTintColor = UIColor.blue
moviesDataProvider = MoviesCoreDataProvider(with: self)
loadMovies()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.backgroundColor = UIViewController.themeColor
}
// MARK: - Private methods
private func loadMovies() {
moviesDataProvider?.fetch { [weak self] error, loadedMovies in
if error == nil {
self?.movies = loadedMovies ?? []
DispatchQueue.main.async {
self?.tableView.reloadData()
}
} else {
debugPrint("Error fetching movies")
}
}
}
private func confirmDelete(at indexPath: IndexPath) {
let movie = movies[indexPath.row]
let title = Localization.deleteMovieConfirm(movie.title!)
let confirmActionSheet = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
let deleteAction = UIAlertAction(title: Localization.delete, style: .destructive) {[weak self] action in
_ = self?.moviesDataProvider?.delete(object: movie)
}
let dismissAction = UIAlertAction(title: Localization.cancel, style: .default) { action in
self.dismiss(animated: true, completion: nil)
}
confirmActionSheet.addAction(deleteAction)
confirmActionSheet.addAction(dismissAction)
self.present(confirmActionSheet, animated: true, completion: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destVc = segue.destination as? MovieDetailViewController {
destVc.movie = self.selectedMovie
}
}
}
extension MoviesTableViewController: UIGestureRecognizerDelegate {}
// MARK: - Table view data source
extension MoviesTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
self.tableView.backgroundView = nil
let counter = movies.count
if counter == 0 {
self.tableView.backgroundView = self.emptyDataView
return 0
}
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let movie = movies[indexPath.row]
let cll = tableView.dequeueReusableCell(withIdentifier: MovieTableViewCell.cellIdentifier)
if let cell = cll as? MovieTableViewCell {
cell.prepareCell(with: movie)
return cell
}
let cell = UITableViewCell()
cell.detailTextLabel?.text = "Teste"
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, editActionsForRowAt idxP: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .destructive, title: "Excluir") {[weak self] row, indexPath in
self?.confirmDelete(at: indexPath)
}
return [deleteAction]
}
}
// MARK: - Table view delegate
extension MoviesTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let movie = movies[indexPath.row]
self.selectedMovie = movie
self.performSegue(withIdentifier: "movieDetailSegue", sender: nil)
}
}
extension MoviesTableViewController: MoviesCoreDataProviderDelegate {
func dataDidChange() {
self.loadMovies()
}
}
|
//
// ViewController.swift
// F-app
//
// Created by Hoang Truong on 1/16/20.
// Copyright © 2020 Hoang Truong. All rights reserved.
//
import UIKit
import Firebase
class HomeVC: UIViewController
//UICollectionViewDataSource,UICollectionViewDelegate
{
var postFeeds: [DesignPost] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//read data from cloud
func loadDesigns() {
//Order data
// set the array to empty to clear dummay array
// db.collection(K.FStore.collectionName)
// .order(by: K.FStore.dateField)
// .addSnapshotListener { (querySnapshot, error) in
//
// self.messages = [] // clear out all exsiting data to avoid duplication when retriving the data from the database
//
// if let e = error {
// print ("There was an issue retrieving data from Firestore, \(e)")
// } else {
// if let snapShotDocuments = querySnapshot?.documents {
// for doc in snapShotDocuments {
// // loop through all the data in the document
//
// let data = doc.data()// print out the data in the document
//
// // down cast the optional String
// if let messageSender = data[K.FStore.senderField] as? String, let messageBody = data[K.FStore.bodyField] as? String {
// let newMessage = Message(sender: messageSender, body: messageBody) // set the new message
// self.messages.append(newMessage) // add new messages into the array
//
// DispatchQueue.main.async {
// self.tableView.reloadData() // tap into tablevIew, and trigger Datasource again
//
//
// //Scroll to the last item in the table view
// let indexPath = IndexPath(row: self.messages.count - 1, section: 0)
// self.tableView.scrollToRow(at: indexPath, at: .top, animated: false)
//
//
//
// } // fetch the data in the background
//
// }
//
// }
// }
// }
// }
}
// MARK:- Collection View delegate method
// func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//
// }
//
//
//
// // MARK:- UI Collection Datasource protocol
//
// func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// return postFeeds.count
// }
//
// func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// let post = postFeeds[indexPath.row]
// let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "designPostCell", for: indexPath) as! DesignerPostCell
// cell.userName = postFeeds
//
// return cell
// }
}
|
//
// TransactionHeaderViewCollectionViewController.swift
// RoundUpFeature_StarlingBank
//
// Created by Muhammad Shahrukh on 6/27/19.
// Copyright © 2019 Muhammad Shahrukh. All rights reserved.
//
import UIKit
protocol HeaderViewDelegate {
func didTapSaveToGoals()
func didTapLogout()
}
class TransactionHeaderView: UITableViewHeaderFooterView {
var delegate: HeaderViewDelegate?
var userDetails: UserDetails? {
didSet {
guard let uid = userDetails?.accountUid else {return}
let attributedText = NSMutableAttributedString(string: "Uid: ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black])
attributedText.append(NSAttributedString(string: uid, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white]))
uidLabel.attributedText = attributedText
}
}
var accountDetails: AccountDetails? {
didSet {
guard let accountNumber = accountDetails?.accountIdentifier else {return}
let attributedText = NSMutableAttributedString(string: "Account No: ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black])
attributedText.append(NSAttributedString(string: accountNumber, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white]))
accountNumberLabel.attributedText = attributedText
}
}
var accountBalance: Amount? {
didSet {
guard let balanceInUnits = accountBalance?.minorUnits else {return}
let balanceInPounds = convertMinorUnitsIntToPoundsCGFloat(number: balanceInUnits)
let attributedText = NSMutableAttributedString(string: "Balance: ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black])
attributedText.append(NSAttributedString(string: "£\(balanceInPounds)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white]))
balanceLabel.attributedText = attributedText
}
}
var roundUpAmount: CGFloat? {
didSet{
guard let amount = roundUpAmount else {return}
let formattedRoundUpAmount = String(format: "%0.2f", amount)
let attributedText = NSMutableAttributedString(string: "Total Round Up: ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.black])
attributedText.append(NSAttributedString(string: "£\(formattedRoundUpAmount)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .heavy), NSAttributedString.Key.foregroundColor: UIColor.white]))
roundUpAmountLabel.attributedText = attributedText
}
}
lazy var logoutButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "logout.png")?.withRenderingMode(.alwaysOriginal), for: .normal)
button.imageView?.contentMode = .scaleAspectFill
button.layer.cornerRadius = 15
button.addTarget(self, action: #selector(handleLogout), for: .touchUpInside)
button.alpha = 0.5
return button
}()
@objc func handleLogout() {
print(123)
delegate?.didTapLogout()
}
lazy var logoImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "starlingLogo.PNG")?.withRenderingMode(.alwaysOriginal)
iv.contentMode = .scaleAspectFit
iv.clipsToBounds = true
return iv
}()
lazy var uidLabel: UILabel = {
let label = UILabel()
let attributedText = NSMutableAttributedString(string: "Uid: ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: UIColor.black])
attributedText.append(NSAttributedString(string: "", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: UIColor.white]))
label.attributedText = attributedText
label.textAlignment = .center
return label
}()
lazy var accountNumberLabel: UILabel = {
let label = UILabel()
let attributedText = NSMutableAttributedString(string: "Account No: ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black])
attributedText.append(NSAttributedString(string: "", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white]))
label.attributedText = attributedText
return label
}()
lazy var balanceLabel: UILabel = {
let label = UILabel()
let attributedText = NSMutableAttributedString(string: "Balance: ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black])
attributedText.append(NSAttributedString(string: "", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white]))
label.attributedText = attributedText
return label
}()
lazy var horizantalStackView: UIStackView = {
let sv = UIStackView(arrangedSubviews: [accountNumberLabel, balanceLabel])
sv.alignment = .center
sv.axis = .horizontal
sv.spacing = 20
return sv
}()
lazy var overallStackView = UIStackView(arrangedSubviews: [uidLabel, horizantalStackView])
let roundUpAmountLabel: UILabel = {
let label = UILabel()
label.text = "Total Round Up: "
label.font = UIFont.systemFont(ofSize: 20, weight: .bold)
label.textAlignment = .center
return label
}()
lazy var saveToGoalButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("SAVE TO GOALS", for: .normal)
button.setTitleColor(#colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1), for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .bold)
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
button.backgroundColor = .white
button.alpha = 0.5
button.layer.cornerRadius = 15
button.addTarget(self, action: #selector(handleRoundUp), for: .touchUpInside)
return button
}()
@objc func handleRoundUp() {
delegate?.didTapSaveToGoals()
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
setupViews()
}
func setupViews() {
overallStackView.axis = .vertical
overallStackView.distribution = .fillEqually
overallStackView.alignment = .center
addSubview(logoutButton)
addSubview(logoImageView)
addSubview(horizantalStackView)
addSubview(roundUpAmountLabel)
addSubview(saveToGoalButton)
logoutButton.anchor(top: topAnchor, leading: nil, bottom: nil, trailing: trailingAnchor, padding: .init(top: 25, left: 0, bottom: 0, right: 25), size: .init(width: 40, height: 40))
logoImageView.anchor(top: nil, leading: nil, bottom: horizantalStackView.topAnchor, trailing: nil, padding: .init(top: 0, left: 0, bottom: 20, right: 0), size: .init(width: frame.width, height: 60))
logoImageView.centerXInSuperview()
horizantalStackView.anchor(top: nil, leading: nil, bottom: roundUpAmountLabel.topAnchor, trailing: nil, padding: .zero, size: .init(width: frame.width, height: 30))
horizantalStackView.centerXInSuperview()
roundUpAmountLabel.anchor(top: nil, leading: leadingAnchor, bottom: saveToGoalButton.topAnchor, trailing: trailingAnchor, padding: .init(top: 0, left: 0, bottom: 15, right: 0), size: .init(width: 0, height: 30))
roundUpAmountLabel.centerXInSuperview()
saveToGoalButton.anchor(top: nil, leading: nil, bottom: bottomAnchor, trailing: nil, padding: .init(top: 0, left: 0, bottom: 25, right: 0), size: .init(width: 190, height: 50))
saveToGoalButton.centerXInSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ViewModel.swift
// Reminder Clone
//
// Created by Elias Lankinen on 7/21/20.
// Copyright © 2020 Elias Lankinen. All rights reserved.
//
import SwiftUI
class ViewModel: ObservableObject {
@Published private var listItems = Array<ListItem>()
var items: Array<ListItem> {
listItems
}
func addItem(_ label: String) {
listItems.append(ListItem(label))
}
}
|
//
// RegisterProfileViewController.swift
// Boatell-x-v2
//
// Created by Austin Potts on 3/26/20.
// Copyright © 2020 Potts Evolvements. All rights reserved.
//
import UIKit
import Firebase
class RegisterProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet var emailTextField: UITextField!
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
@IBOutlet weak var imager: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
signUpButton.layer.cornerRadius = 20
}
@IBAction func signUpTapped(_ sender: Any) {
handleRegister()
}
func handleRegister() {
guard let email = emailTextField.text, let password = passwordTextField.text, let name = usernameTextField.text else { return }
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if let error = error {
print("Error: \(error)")
return
}
guard let uid = user?.user.uid else { return }
let imageName = NSUUID().uuidString
let storageRef = Storage.storage().reference().child("\(imageName).png")
if let uploadData = self.imager.image?.pngData() {
storageRef.putData(uploadData, metadata: nil) { (metadata, error) in
if let error = error {
print("Error uploading image data: \(error)")
return
}
storageRef.downloadURL { (url, error) in
if let error = error {
print("Error downloading URL: \(error)")
return
}
if let profileImageUrl = url?.absoluteString {
let values = ["name": name, "email": email, "profileImageURL": profileImageUrl ]
self.registerUserIntoDatabaseWithUID(uid: uid, values: values as [String : AnyObject])
}
}
// print(metadata)
}
}
}
}
private func registerUserIntoDatabaseWithUID(uid: String, values: [String: AnyObject]) {
// Successfully Registered Value
var ref: DatabaseReference!
ref = Database.database().reference(fromURL: "https://boatell-v2.firebaseio.com/")
let userRef = ref.child("users").child(uid)
// let values = ["name": name, "email": email, "profileImageURL": metadata.downloadURL()]
userRef.updateChildValues(values) { (error, refer) in
if let error = error {
print("error child values: \(error)")
return
}
print("Saved user successfully into firebase db")
}
}
@IBAction func cameraButtonTapped(_ sender: Any) {
let picker = UIImagePickerController()
picker.allowsEditing = false
picker.delegate = self
picker.sourceType = .photoLibrary
present(picker, animated: true)
}
@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer) {
view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension RegisterProfileViewController {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true)
guard let image = info[.originalImage] as? UIImage else {
return
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 227, height: 227), true, 2.0)
image.draw(in: CGRect(x: 0, y: 0, width: 414, height: 326))
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary
var pixelBuffer : CVPixelBuffer?
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(newImage.size.width), Int(newImage.size.height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer)
guard (status == kCVReturnSuccess) else {
return
}
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: pixelData, width: Int(newImage.size.width), height: Int(newImage.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) //3
context?.translateBy(x: 0, y: newImage.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
UIGraphicsPushContext(context!)
newImage.draw(in: CGRect(x: 0, y: 0, width: newImage.size.width, height: newImage.size.height))
UIGraphicsPopContext()
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
imager.image = newImage
}
}
|
//
// CollectionViewController.swift
// UITableViewDemo
//
// Created by apple on 2017/8/31.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
class CollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
var cellIdentifier = "MyCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.title = "Collection"
let width = self.view.frame.size.width
let height = self.view.frame.size.height
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width:80,height:80)
//列间距,行间距,偏移
layout.minimumInteritemSpacing = 15
layout.minimumLineSpacing = 10
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
let collectionView = UICollectionView(frame: CGRect(x:0, y:0, width: width, height: height), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.white
collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
self.view.addSubview(collectionView)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - delegate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! MyCollectionViewCell
cell.backgroundColor = UIColor.red
cell.titleLabel.text = "Hello"
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item % 2 == 0 {
print("click indexPath.item", indexPath.item)
}else{
self.navigationController?.popViewController(animated: true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ListViewController.swift
// MixedUILibrariesSampleyusaku
//
// Created by 藤田優作 on 2019/11/17.
// Copyright © 2019 藤田優作. All rights reserved.
//
import UIKit
import VegaScrollFlowLayout
class ListViewController: UIViewController {
//UI部品の配置
@IBOutlet weak var listCollectionView: UICollectionView!
fileprivate var listContents: [List] = [] {
didSet {
self.listCollectionView.reloadData()
}
}
//CollectionView表示の隙間やサイズに関する設定
private
let itemHeight: CGFloat = 180
private let lineSpacing: CGFloat = 15
private let spaceInset: CGFloat = 15
private let topInset: CGFloat = 10
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupListCollectionViewCell()
setupListCollectionViewLayout()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
private func setupNavigationBar() {
removeBackButtonText()
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.title = "クリスマスの食べたいディナー"
}
private func setupListCollectionViewCell() {
listCollectionView.delegate = self
listCollectionView.dataSource = self
listCollectionView.register(ListCollectionViewCell.self)
//リスト用のUICollectionViewの下部をセルの高さ分マージンを開ける
listCollectionView.contentInset.bottom = itemHeight
listContents = List.getSampleData()
}
private func setupListCollectionViewLayout() {
//表示するセルのサイズや隙間に関する値の設定をする
guard let layout = listCollectionView.collectionViewLayout as? VegaScrollFlowLayout else {
return
}
layout.minimumLineSpacing = lineSpacing
layout.sectionInset = UIEdgeInsets(top: topInset, left: 0, bottom: 0, right: 0)
let itemWidth = UIScreen.main.bounds.width - 2 * spaceInset
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
listCollectionView.collectionViewLayout.invalidateLayout()
}
}
extension ListViewController:UICollectionViewDataSource,UICollectionViewDelegate{
func collectionView(_ collectionVew: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionVew.dequeueReusableCustomCell(with: ListCollectionViewCell.self, indexPath: indexPath)
let list = listContents[indexPath.row]
cell.setCell(list)
return cell
}
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
return listContents.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "ToArticleViewController", sender: self)
}
}
|
//
// ViewController.swift
// ExampleForUIWindows
//
// Created by Luke Yin on 2019-12-03.
// Copyright © 2019 Luke Yin. All rights reserved.
//
import UIKit
import UIWindows
class ViewController: UIViewController {
var desktop: UIDesktop!
var menuViewController: MenuViewController!
var menuWindow: UIWindowsWindow!
var documentPickerViewController: UIDocumentPickerViewController!
var documentPickerWindow: UIWindowsWindow!
var imagePickerController: UIImagePickerController!
var imagePickerWindow: UIWindowsWindow!
var cameraController: UIImagePickerController!
var cameraWindow: UIWindowsWindow!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .black
self.desktop = UIDesktop(makeViewControllerAsDesktop: self)
desktop.delegate = self
// setup menu
self.menuViewController = MenuViewController(nibName: "MenuViewController", bundle: nil)
self.menuWindow = UIWindowsWindow(childVC: self.menuViewController, with: .defaultConfig)
// set up document
setupDocument()
// setup image picker
setupImagePicker()
// setup camera
setupCamera()
}
func setupImagePicker() {
self.imagePickerController = UIImagePickerController()
self.imagePickerController.delegate = self
self.imagePickerController.allowsEditing = true
self.imagePickerController.mediaTypes = ["public.image", "public.movie"]
self.imagePickerController.sourceType = .photoLibrary
self.imagePickerWindow = UIWindowsWindow(childVC: imagePickerController, with: .defaultConfig)
}
func setupDocument(){
self.documentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.content", "public.text", "public.source-code ", "public.image", "public.audiovisual-content", "com.adobe.pdf", "com.apple.keynote.key", "com.microsoft.word.doc", "com.microsoft.excel.xls", "com.microsoft.powerpoint.ppt"], in: .open)
self.documentPickerViewController.delegate = self
self.documentPickerWindow = UIWindowsWindow(childVC: self.documentPickerViewController, with: .defaultConfig)
}
func setupCamera(){
self.cameraController = UIImagePickerController()
self.cameraController.delegate = self
self.cameraController.allowsEditing = true
self.cameraController.mediaTypes = ["public.image", "public.movie"]
self.cameraController.sourceType = .camera
self.cameraWindow = UIWindowsWindow(childVC: cameraController, with: .defaultConfig)
}
override func viewDidAppear(_ animated: Bool) {
self.desktop.add(new: self.menuWindow)
menuViewController.configCells(callBack: self)
}
func removeWindow(contain picker:UIImagePickerController) {
if picker == self.imagePickerController {
self.imagePickerWindow.closeWindow()
self.setupImagePicker()
}
if picker == self.cameraController {
self.cameraWindow.closeWindow()
self.setupCamera()
}
}
}
protocol ViewControllerCallBackDelegate {
func createImageWindow(using image: UIImage)
func createDocumentWindow()
func createImagePickerWindow()
func createCameraWindow()
}
extension ViewController: ViewControllerCallBackDelegate {
func createImagePickerWindow() {
self.desktop.add(new: self.imagePickerWindow)
}
func createCameraWindow() {
self.desktop.add(new: self.cameraWindow)
}
func createDocumentWindow() {
self.desktop.add(new: self.documentPickerWindow)
}
func createImageWindow(using image: UIImage) {
let imageViewController = ImageViewController(nibName: "ImageViewController", bundle: nil)
imageViewController.image = image
let imageWindow = UIWindowsWindow(childVC: imageViewController, with: .defaultConfig)
self.desktop.add(new: imageWindow)
}
}
extension ViewController: UIImagePickerControllerDelegate {
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
return
}
public func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
guard let image = info[.editedImage] as? UIImage else {
return
}
self.createImageWindow(using: image)
self.removeWindow(contain: picker)
}
}
extension ViewController: UINavigationControllerDelegate { }
extension ViewController: UIDocumentPickerDelegate { }
extension ViewController: UIDesktopDelegate {
func destop(desktop: UIDesktop, shouldClose window: UIWindowsWindow) -> Bool {
return !(window.childVC is MenuViewController)
}
}
|
//
// AddKYCTableViewController.swift
// TheDocument
//
// Created by Scott Kacyn on 2/14/18.
// Copyright © 2018 Refer To The Document. All rights reserved.
//
import UIKit
class AddKYCTableViewController: UITableViewController {
@IBOutlet weak var verifyButton: UIButton!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var resendButton: UIButton!
var phoneNumber: String?
override func viewDidLoad() {
super.viewDidLoad()
self.addDoneButtonOnKeyboard()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func resendButtonTapped(_ sender: Any) {
self.verifyButton.isEnabled = false
self.resendButton.isEnabled = false
self.resendButton.setTitle("Sending verification text...", for: .normal)
guard let userRef = currentUser.synapseData, let documents = userRef["documents"] as? [[String: Any]], let phones = userRef["phone_numbers"] as? [String], let phoneNumber = phones.first else {
log.debug("No docs or no permissions or no phone")
return
}
var phoneDoc: [String: Any] = [:]
var mainDoc: [String: Any] = [:]
documents.forEach { document in
if let socialDocs = document["social_docs"] as? [[String: Any]] {
socialDocs.forEach { doc in
if let type = doc["document_type"] as? String, type == "PHONE_NUMBER_2FA" {
phoneDoc = doc
mainDoc = document
}
}
}
}
guard let documentId = mainDoc["id"] as? String else { log.debug("Could not find the main document"); return }
guard let phoneDocumentId = phoneDoc["id"] as? String else { log.debug("Could not find the PHONE_NUMBER_2FA document"); return }
API().resendPhoneKYC(documentId: documentId, phoneNumber: phoneNumber, phoneDocumentId: phoneDocumentId) { success in
DispatchQueue.main.async {
self.verifyButton.isEnabled = true
self.resendButton.isEnabled = true
if (success) {
self.resendButton.setTitle("Verification text sent!", for: .normal)
} else {
self.resendButton.setTitle("Unable to send text. Tap here to try again.", for: .normal)
}
}
}
}
@IBAction func buttonTapped(_ sender: Any) {
verifyButton.setTitle("Verifying...", for: .normal)
verifyButton.isEnabled = false
guard let code = textField.text else { showAlert(message: "Please enter the verification code that was sent to your phone"); return }
guard let userRef = currentUser.synapseData, let documents = userRef["documents"] as? [[String: Any]], let phones = userRef["phone_numbers"] as? [String], let phone = phones.first else {
log.debug("No docs or no permissions or phones")
return
}
var phoneDoc: [String: Any] = [:]
var mainDoc: [String: Any] = [:]
documents.forEach { document in
if let socialDocs = document["social_docs"] as? [[String: Any]] {
socialDocs.forEach { doc in
if let type = doc["document_type"] as? String, type == "PHONE_NUMBER_2FA" {
phoneDoc = doc
mainDoc = document
}
}
}
}
guard let documentId = mainDoc["id"] as? String else { log.debug("Could not find the main document"); return }
guard let phoneDocumentId = phoneDoc["id"] as? String else { log.debug("Could not find the PHONE_NUMBER_2FA document"); return }
API().updatePhoneKYC(documentId: documentId, phoneNumber: phone, phoneDocumentId: phoneDocumentId, code: code) { success in
if (success) {
log.info("Was able to successfully update phone number!")
self.complete()
} else {
log.debug("Unable to update phone KYC")
}
}
}
func complete() {
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
@IBAction func closeModal(_ sender: Any) {
DispatchQueue.main.async {
self.navigationController!.dismiss(animated: true, completion: nil)
}
}
@objc func doneButtonAction() {
self.view.endEditing(true)
}
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
doneToolbar.barTintColor = Constants.Theme.mainColor
doneToolbar.tintColor = .white
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Close", style: .done, target: self, action: #selector(AddKYCTableViewController.doneButtonAction))
var items = [UIBarButtonItem]()
items.append(flexSpace)
items.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
self.textField.inputAccessoryView = doneToolbar
}
}
extension AddKYCTableViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
extension Accessory {
open class Fan: Accessory {
public let fan = Service.Fan()
public init(info: Service.Info) {
super.init(info: info, type: .fan, services: [fan])
}
}
}
extension Service {
public class Fan: Service {
open let on = GenericCharacteristic<On>(type: .on, value: false)
public init() {
super.init(type: .fan, characteristics: [on])
}
}
}
|
//
// StringExtension.swift
// 密语输入法
//
// Created by macsjh on 15/12/2.
// Copyright © 2015年 macsjh. All rights reserved.
//
import Foundation
extension String
{
func subString(fromIndex:Int, length:Int) -> String
{
let temp = NSString(string: self)
let tempFrom = NSString(string: temp.substringFromIndex(fromIndex))
return tempFrom.substringToIndex(length)
}
///返回给定字符串在本串中的位置,不存在返回-1
func indexOf(string: String) -> Int
{
let range = NSString(string: self).rangeOfString(string)
if(range.length < 1)
{
return -1
}
return range.location
}
var intValue:Int?
{
get{
return NSNumberFormatter().numberFromString(self)?.integerValue
}
}
///将表示十六进制数据的字符串转换为对应的二进制数据
///
///- Parameter string:形如“6E7C2F”的字符串
///- Returns: 对应的二进制数据
public func hexStringToData() ->NSData?
{
let hexString:NSString = self.uppercaseString.stringByReplacingOccurrencesOfString(" ", withString:"")
if (hexString.length % 2 != 0) {
return nil
}
var tempbyt:[UInt8] = [0]
let bytes = NSMutableData(capacity: hexString.length / 2)
for(var i = 0; i < hexString.length; ++i)
{
let hex_char1:unichar = hexString.characterAtIndex(i)
var int_ch1:Int
if(hex_char1 >= 48 && hex_char1 <= 57)
{
int_ch1 = (Int(hex_char1) - 48) * 16
}
else if(hex_char1 >= 65 && hex_char1 <= 70)
{
int_ch1 = (Int(hex_char1) - 55) * 16
}
else
{
return nil;
}
i++;
let hex_char2:unichar = hexString.characterAtIndex(i)
var int_ch2:Int
if(hex_char2 >= 48 && hex_char2 <= 57)
{
int_ch2 = (Int(hex_char2) - 48)
}
else if(hex_char2 >= 65 && hex_char2 <= 70)
{
int_ch2 = Int(hex_char2) - 55;
}
else
{
return nil;
}
tempbyt[0] = UInt8(int_ch1 + int_ch2)
bytes!.appendBytes(tempbyt, length:1)
}
return bytes;
}
} |
//
// Alerts.swift
// GitHub
//
// Created by Zerone on 03/02/20.
// Copyright © 2020 thobio. All rights reserved.
//
import UIKit
class AlertsView {
func showSimpleAlert(message:String,head:String,vc:UIViewController,buttonName:String) {
let alert = UIAlertController(title: head, message: message,preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonName, style: .default, handler: { _ in
}))
vc.present(alert, animated: true, completion: nil)
}
}
|
import Foundation
@objc class SmartyLogger: NSObject {
@objc func log(message: String) {
NSLog("%@", "\n\(message)")
}
}
|
func findIndArray(arrayToBeSearchedFrom : [Int], valueToBeSearched : Int = 0) -> Int? {
var array = arrayToBeSearchedFrom
var index = 0
var value = valueToBeSearched
while index < array.count {
if(array[index] == value){
return index
}
index += 1
}
return nil
}
let value1 = findIndArray(arrayToBeSearchedFrom: [2,0,3,4])
let value2 = findIndArray(arrayToBeSearchedFrom: [0,2,3,4], valueToBeSearched: 4)
print(value1!) // 1
print(value2!) // 3 |
//
// Meal+CoreDataProperties.swift
//
//
// Created by Vinicius Mangueira on 04/07/19.
//
//
import CoreData
struct ScheduleInfo {
enum ScheduleType: String {
case breakfast = "BreakFast"
case lunch = "Lunch"
case dinner = "Dinner"
case none
}
static func getSchedule(_ schedule: String) -> ScheduleType {
if schedule == ScheduleSection.breakfast.rawValue {
return .breakfast
} else if schedule == ScheduleSection.lunch.rawValue {
return .lunch
} else if schedule == ScheduleSection.dinner.rawValue {
return .dinner
}
return .none
}
}
extension Meal {
convenience init(name: String, imageData: Data, timestamp: Int32) {
self.init()
self.name = name
self.imageData = imageData
self.timestamp = timestamp
}
@nonobjc public class func fetchRequest() -> NSFetchRequest<Meal> {
return NSFetchRequest<Meal>(entityName: "Meal")
}
@NSManaged public var name: String?
@NSManaged public var imageData: Data
@NSManaged public var timestamp: Int32
@NSManaged public var schedule: String?
func setSchedule() {
if self.timestamp >= 0 || self.timestamp <= 12 {
schedule = ScheduleSection.breakfast.rawValue
} else if self.timestamp >= 13 || self.timestamp <= 18 {
schedule = ScheduleSection.lunch.rawValue
} else {
schedule = ScheduleSection.dinner.rawValue
}
}
}
enum ScheduleSection: String {
case breakfast = "BreakFast"
case lunch = "Lunch"
case dinner = "Dinner"
}
|
// public func playSound(_ type:SoundType){
// commandSender.playSound(type)
// }
public func connectToRobot(_ name:String){
commandSender.connectToRobot(name)
}
public func exitProgram(){
commandSender.exitProgram()
}
public func moveForward(){
commandSender.moveForward()
}
// public func moveBackward(){
// commandSender.moveBackward()
// }
// public func turnRight(){
// commandSender.turnRight()
// }
// public func turnLeft(){
// commandSender.turnLeft()
// }
// public func playSoundCarEngine(){
// commandSender.playSoundCarEngine()
// }
// public func playSoundHi(){
// commandSender.playSoundHi()
// }
// public func setLight(_ type:ColorType){
// commandSender.setLight(type)
// }
// public func isObstacleInFront()->Bool{
// return commandSender.getSensorInFront()
// }
// public func isObstacleInRear()->Bool{
// return commandSender.getSensorInRear()
// }
// public func waitForObstacleInFront(){
// commandSender.waitForObstacleInFront()
// }
// public func waitForObstacleInRear(){
// commandSender.waitForObstacleInRear()
// }
// public func waitForClap(){
// commandSender.waitForClap()
// }
// public func waitForButton1Press(){
// commandSender.waitForButton1Press()
// }
// public func waitForButton2Press(){
// commandSender.waitForButton2Press()
// }
// public func waitForButton3Press(){
// commandSender.waitForButton3Press()
// }
|
//
// TouchandFaceAuthenticationViewController.swift
// Manawadu M.S-Cobsccomp171p008
//
// Created by Sandeepa Manawadu on 2019/05/23.
// Copyright © 2019 Sandeepa Manawadu. All rights reserved.
//
import UIKit
import LocalAuthentication
class TouchandFaceAuthenticationViewController: UIViewController {
let context: LAContext = LAContext()
@IBOutlet weak var authenticateBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// checking the authentication type
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
{
if context.biometryType == .faceID {
authenticateBtn.setImage(UIImage(named: "face"), for: UIControl.State.normal)
} else if context.biometryType == .touchID {
authenticateBtn.setImage(UIImage(named: "touch"), for: UIControl.State.normal)
}
}
// giving the UI title
self.title = "My Profile"
}
@IBAction func doButtonAuthenticate(_ sender: UIButton) {
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
context.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Identify yourself!") { (correct, nil) in
if correct {
DispatchQueue.main.async {
// go to the next screen
self.performSegue(withIdentifier: "userProfileView", sender: self)
}
} else {
print("Invalid Password")
}
}
} else {
print("Doesn't support Biometric Authentication ")
}
}
}
|
//
// ViewController.swift
// eKing
//
// Created by NguyenXuan-Gieng on 5/26/16.
// Copyright © 2016 Xuan-Gieng Nguyen. All rights reserved.
//
import Photos
import UIKit
import Firebase
import SCLAlertView
import LTMorphingLabel
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, LTMorphingLabelDelegate {
@IBOutlet weak var pictureView: UIImageView!
@IBOutlet weak var deviceNameLabel: UILabel!
@IBOutlet weak var loadingTextLabel: LTMorphingLabel!
var storageRef: FIRStorageReference!
var databaseRef: FIRDatabaseReference!
// loading texts array
let uploadingTexts = ["You've just done a great thing!",
"I'm sending your picture...",
"...to your display",
"It's such a beautiful picture!",
"As you are today...",
"Have a great day!",
"Thanks for using me!",
"I will always make myself better",
"And if I take you a long time, ...",
"o..",
".o.",
"..o",
"Sorry for the low connection 😭",
""]
private var textUploadingIndex = -1
var animatedUploadingText: String {
textUploadingIndex = textUploadingIndex >= uploadingTexts.count - 1 ? 0 : textUploadingIndex + 1
return uploadingTexts[textUploadingIndex]
}
// do downloading later
var isUploading = false
var isDownloading = false
// Test value
let deviceId = "testDevice"
override func viewDidLoad() {
super.viewDidLoad()
// configure firebase
configureStorage()
configureDatabase()
// configure loading label
loadingTextLabel.delegate = self
loadingTextLabel.morphingEffect = .Evaporate
// show previous picture
getShowingPictureOnDevice(deviceId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onPicturePressed(sender: AnyObject) {
let picker = UIImagePickerController()
picker.delegate = self
// ask people to chose where to select picture
let alertViewIcon = UIImage(named: "splash")
let appearance = SCLAlertView.SCLAppearance(
showCloseButton: false
)
let alertView = SCLAlertView(appearance: appearance)
alertView.addButton("Library") {
print("Lib button tapped")
picker.sourceType = .PhotoLibrary
self.presentViewController(picker, animated: true, completion:nil)
}
if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
alertView.addButton("Camera") {
print("Camera button tapped")
picker.sourceType = .Camera
self.presentViewController(picker, animated: true, completion:nil)
}
}
alertView.showSuccess("Great!", subTitle: "So, where do you want to pick from?", circleIconImage: alertViewIcon)
}
func configureStorage() {
storageRef = FIRStorage.storage().referenceForURL("gs://project-764193416932776084.appspot.com")
}
func configureDatabase() {
databaseRef = FIRDatabase.database().reference()
}
func beginUploading(timeInterval: Float){
isUploading = true
// change text:
textUploadingIndex = -1
loadingTextLabel.text = animatedUploadingText
}
func doneUploading() {
loadingTextLabel.text = "Well done!";
isUploading = false
}
func loadImageFromURL(imageUrl: String, loadCompletion: (UIImage) -> Void) {
if imageUrl.hasPrefix("gs://") {
FIRStorage.storage().referenceForURL(imageUrl).dataWithMaxSize(INT64_MAX){ (data, error) in
if let error = error {
print("Error downloading: \(error)")
return
}
if let resultImage = UIImage.init(data: data!) {
loadCompletion(resultImage)
}
}
} else if let url = NSURL(string:imageUrl), data = NSData(contentsOfURL: url) {
if let resultImage = UIImage.init(data: data) {
loadCompletion(resultImage)
}
}
}
func getShowingPictureOnDevice(deviceId: String) {
databaseRef.child("devices").child(deviceId).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let url = snapshot.value!["imageURL"] as! String
print(url)
// load image from url, then show it up
self.loadImageFromURL(url, loadCompletion: self.transitionToNextPicture)
}) { (error) in
print(error.localizedDescription)
// there is no pic, invite user to pick one.
}
}
func transitionToNextPicture(nextImage nextImage: UIImage) {
let animationDuration = 0.5
CATransaction.begin()
CATransaction.setAnimationDuration(animationDuration)
let transition = CATransition()
//transition.type = kCATransitionFade
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
pictureView.layer.addAnimation(transition, forKey: kCATransition)
pictureView.image = nextImage
CATransaction.commit()
}
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject]) {
picker.dismissViewControllerAnimated(true, completion:nil)
// the same function in 2 cases below:
// save it it on cloud
func saveUrlToCloud(metadata:FIRStorageMetadata?){
var newImg = ["changedTime" : "", "imageURL" : ""]
newImg["changedTime"] = NSDate().toString()
newImg["imageURL"] = self.storageRef.child((metadata?.path)!).description
self.databaseRef.child("devices").child(self.deviceId).setValue(newImg)
}
beginUploading(0)
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageData = UIImageJPEGRepresentation(image, 0.8)
let imagePath = "\(self.deviceId)/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000)).jpg"
// store on cloud
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
self.storageRef.child(imagePath)
.putData(imageData!, metadata: metadata) { (metadata, error) in
if let error = error {
print("Error uploading: \(error)")
return
}
// do something if upload pic successfully
print(self.storageRef.child((metadata?.path)!).description)
// save it it on cloud
saveUrlToCloud(metadata)
// show on screen
self.transitionToNextPicture(nextImage: image)
// done
self.doneUploading()
}
}
}
extension ViewController {
func morphingDidStart(label: LTMorphingLabel) {
}
func morphingDidComplete(label: LTMorphingLabel) {
if isUploading {
loadingTextLabel.text = animatedUploadingText
} else if isDownloading {
// do it later
} else {
loadingTextLabel.text = ""
}
}
func morphingOnProgress(label: LTMorphingLabel, progress: Float) {
}
}
|
import XCTest
import UITestsCore
public struct DefaultElementValidator<Element: NSObject>: ElementValidator {
public typealias Object = Element
public init() {}
}
extension ElementValidator {
public func verify(_ object: Object, using predicates: [Predicate], timeout: TimeInterval = .timeout, file: StaticString, line: UInt) {
if validate(object, using: predicates, timeout: timeout) == false {
XCTFail("[\(self)] Element \(object.description) did not fulfill expectation: \(predicates.map(\.format))",
file: file,
line: line)
}
}
public func validate(_ object: Object, using predicates: [Predicate], timeout: TimeInterval) -> Bool {
let expectation = XCTNSPredicateExpectation(predicate: predicates.predicate, object: object)
return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed
}
}
extension ElementValidator where Object == XCUIElementQuery {
func contains(_ element: Object, predicates: [Predicate], file: StaticString, line: UInt) {
if element.filter(using: predicates).count == 0 {
XCTFail("[\(self)] Element \(element.description) does not contain descendants using: \(predicates.map(\.format)) predicate",
file: file,
line: line)
}
}
func verifyElementCount(_ element: Object, using predicates: [Predicate], count: Int, file: StaticString, line: UInt) {
let query = element.matching(predicates.predicate)
XCTAssertEqual(query.count, count, "[\(self)] Number of elements for \(query.description) is not equal to \(count)", file: file, line: line)
}
}
|
//
// Image.swift
// Model Generated using http://www.jsoncafe.com/
// Created on March 6, 2020
import Foundation
//MARK: - Image
public struct Image {
public var height : Int!
public var url : String!
public var width : Int!
}
|
import Foundation
class Solution {
func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
let nums = nums.sorted()
var minDiff = Int.max
for i in 0..<nums.count - 2 {
var left = i + 1
var right = nums.count - 1
while left < right {
let currentSum = nums[i] + nums[left] + nums[right]
let currentDiff = target - currentSum
if abs(currentDiff) < abs(minDiff) {
minDiff = currentDiff
}
if currentSum < target {
left += 1
} else if currentSum > target {
right -= 1
} else {
return target
}
}
}
return target - minDiff
}
}
|
//
// StartTestButton.swift
// SpeedTest
//
// Created by BabyReebeeDude on 2021-01-13.
//
import UIKit
/// Rename to smth like LoadingButton, with ability to set initial text
@IBDesignable final class StartTestButton: RoundedButton {
@IBInspectable var title: String?
// MARK: - Private Properties
private lazy var indicatorsStackView: UIStackView = {
let loadingIndictorViews = [
RoundedView(color: .white),
RoundedView(color: .white),
RoundedView(color: .white)
]
let indicatorsStackView = UIStackView(arrangedSubviews: loadingIndictorViews)
indicatorsStackView.isUserInteractionEnabled = false
indicatorsStackView.spacing = 8
indicatorsStackView.axis = .horizontal
indicatorsStackView.distribution = .fillEqually
indicatorsStackView.translatesAutoresizingMaskIntoConstraints = false
return indicatorsStackView
}()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
// MARK: - Public Methods
func showLoadingAnimation() {
setTitle(nil, for: .normal)
indicatorsStackView.isHidden = false
let loadingIndicatorViews = indicatorsStackView.arrangedSubviews
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [self] in
loadingIndicatorViews.enumerated().forEach { index, subview in
let nextView = index < loadingIndicatorViews.count - 1 ? loadingIndicatorViews[index + 1] : loadingIndicatorViews[0]
animate(view: subview, to: nextView.center)
}
}
}
func stopLoadingAnimation() {
setTitle(title, for: .normal)
indicatorsStackView.isHidden = true
indicatorsStackView.arrangedSubviews.forEach {
$0.layer.removeAllAnimations()
}
}
}
// MARK: - UI Setup
private extension StartTestButton {
private func setup() {
indicatorsStackView.isHidden = true
addSubview(indicatorsStackView)
NSLayoutConstraint.activate([
indicatorsStackView.arrangedSubviews[0].widthAnchor.constraint(equalTo: indicatorsStackView.arrangedSubviews[0].heightAnchor),
indicatorsStackView.centerYAnchor.constraint(equalTo: centerYAnchor),
indicatorsStackView.centerXAnchor.constraint(equalTo: centerXAnchor),
indicatorsStackView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.05),
])
}
}
// MARK: - Animation Configuration
private extension StartTestButton {
/// Animates `view` from center to `endPoint`
private func animate(view: UIView, to endPoint: CGPoint) {
let animationPath = UIBezierPath()
let startPoint = view.center
animationPath.move(to: startPoint)
if startPoint.x < endPoint.x {
animationPath.addLine(to: endPoint)
} else {
animationPath.addQuadCurve(to: endPoint, controlPoint: CGPoint(x: abs(startPoint.x - endPoint.x) / 2,
y: startPoint.y + bounds.height / 2.5))
}
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = animationPath.cgPath;
animation.fillMode = .forwards
animation.isRemovedOnCompletion = false
animation.duration = 0.6
animation.repeatCount = .infinity
animation.timingFunction = .init(name: .easeInEaseOut)
view.layer.add(animation, forKey: "loading_indicator")
}
}
|
//
// BinaryTree.swift
// OCLeetcode
//
// Created by ght on 2019/3/6.
// Copyright © 2019 youdao. All rights reserved.
//
import Foundation
|
//: Playground - noun: a place where people can play
import UIKit
/// When you assign a default value to a stored property, or set its initial value within an initializer, the value of that property is set directly, without calling any property observers.
struct Fahrenheit {
var temperature: Double = 1
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
print("The default temperature is \(f.temperature)° Fahrenheit")
// Prints "The default temperature is 32.0° Fahrenheit”
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0”
/// “initializers do not have an identifying function name before their parentheses in the way that functions and methods do. Therefore, the names and types of an initializer’s parameters play a particularly important role in identifying which initializer should be called. Because of this, Swift provides an automatic argument label for every parameter in an initializer if you don’t provide one.”
struct Color {
let red, green, blue: Double
init(_ red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
init(white: Double) {
red = white
green = white
blue = white
}
}
let magenta = Color(1.0, green: 0.0, blue: 1.0)
let halfGray = Color(white: 0.5)
/// Optional Property Types
/// “You can assign a value to a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes. Once a constant property is assigned a value, it can’t be further modified.”
/// “For class instances, a constant property can be modified during initialization only by the class that introduces it. It cannot be modified by a subclass.”
/// Default Initializers
/// “Swift provides a default initializer for any structure or class that provides default values for all of its properties and does not provide at least one initializer itself”
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
/// “Memberwise Initializers for Structure Types”
/// “Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers.”
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
/// If you want your custom value type to be initializable with the default initializer and memberwise initializer, and also with your own custom initializers, write your custom initializers in an extension rather than as part of the value type’s original implementation.
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
init() {}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
init(_ center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
/// Designated Initializers and Convenience Initializers
/**
Rule 1
A designated initializer must call a designated initializer from its immediate superclass.
Rule 2
A convenience initializer must call another initializer from the same class.
Rule 3
A convenience initializer must ultimately call a designated initializer.
*/
/// Two-Phase Initialization
/**
Safety check 1
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all of its own properties are initialized before it hands off up the chain.
Safety check 2
A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn’t, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization.
Safety check 3
A convenience initializer must delegate to another initializer before assigning a value to any property (including properties defined by the same class). If it doesn’t, the new value the convenience initializer assigns will be overwritten by its own class’s designated initializer.
Safety check 4
An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization[…]
*/
/**
Phase 1
“A designated or convenience initializer is called on a class.
Memory for a new instance of that class is allocated. The memory is not yet initialized.
A designated initializer for that class confirms that all stored properties introduced by that class have a value. The memory for these stored properties is now initialized.
The designated initializer hands off to a superclass initializer to perform the same task for its own stored properties.
This continues up the class inheritance chain until the top of the chain is reached.
Once the top of the chain is reached, and the final class in the chain has ensured that all of its stored properties have a value, the instance’s memory is considered to be fully initialized, and phase 1 is complete.
Phase 2
Working back down from the top of the chain, each designated initializer in the chain has the option to customize the instance further. Initializers are now able to access self and can modify its properties, call its instance methods, and so on.
Finally, any convenience initializers in the chain have the option to customize the instance and to work with self.”
*/
/// “Initializer Inheritance and Overriding”
/// “You always write the override modifier when overriding a superclass designated initializer, even if your subclass’s implementation of the initializer is a convenience initializer.”
/// Automatic Initializer Inheritance
/**
“Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:
Rule 1
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
Rule 2
If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.
These rules apply even if your subclass adds further convenience initializers.”
*/
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 111)
}
}
let oneMysteryItem = RecipeIngredient()
oneMysteryItem.quantity
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)
/// Failable Initializers
/// “You cannot define a failable and a nonfailable initializer with the same parameter types and names.”
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
let someCreature = Animal(species: "Giraffe")
// someCreature is of type Animal?, not Animal
enum TemperatureUnita {
case kelvin, celsius, fahrenheit
init?(symbol: Character) {
switch symbol {
case "K":
self = .kelvin
case "C":
self = .celsius
case "F":
self = .fahrenheit
default:
return nil
}
}
}
enum TemperatureUnit: Character {
case kelvin = "K", celsius = "C", fahrenheit = "F"
}
let fahrenheitUnit = TemperatureUnit(rawValue: "F")
if fahrenheitUnit != nil {
print("This is a defined temperature unit, so initialization succeeded.")
}
class Product {
let name: String
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}
class CartItem: Product {
let quantity: Int
init?(name: String, quantity: Int) {
if quantity < 1 { return nil }
self.quantity = quantity
super.init(name: name)
}
}
/// “You can override a failable initializer with a nonfailable initializer but not the other way around.”
/// “Note that if you override a failable superclass initializer with a nonfailable subclass initializer, the only way to delegate up to the superclass initializer is to force-unwrap the result of the failable superclass initializer.
class Document {
var name: String?
// this initializer creates a document with a nil name value
init() {}
// this initializer creates a document with a nonempty name value
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}
class AutomaticallyNamedDocument: Document {
override init() {
super.init()
self.name = "[Untitled]"
}
override init(name: String) {
super.init()
if name.isEmpty {
self.name = "[Untitled]"
} else {
self.name = name
}
}
}
class UntitledDocument: Document {
override init() {
super.init(name: "[Untitled]")!
}
}
/// “The init! Failable Initializer”
/// “You can delegate from init? to init! and vice versa”
/// “and you can override init? with init! and vice versa. You can also delegate from init to init!, ”
/// “Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer:”
class SomeClass {
required init() {
// initializer implementation goes here
}
}
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes here
}
}
/// “Setting a Default Property Value with a Closure or Function”
/**
“if you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values. You also cannot use the implicit self property, or call any of the instance’s methods.”
class SomeClass {
let someProperty: SomeType = {
// create a default value for someProperty inside this closure
// someValue must be of the same type as SomeType
return someValue
}()
} */
class Chessboard {
var x:Int!
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...8 {
for j in 1...8 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}()
func squareIsBlackAt(row: Int, column: Int) -> Bool {
return boardColors[(row * 8) + column]
}
} |
//
// String+Utils.swift
// GitHubTest
//
// Created by bruno on 08/02/20.
// Copyright © 2020 bruno. All rights reserved.
//
import UIKit
extension String {
func remove(_ values: [String]) -> String {
var stringValue = self
let toRemove = stringValue.filter { values.contains("\($0)") }
for value in toRemove {
if let range = stringValue.range(of: "\(value)") {
stringValue.removeSubrange(range)
}
}
return stringValue
}
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
func filterOnlyNumbers() -> String {
return String(self.filter { "0123456789".contains($0) })
}
var removeCaracterSpecial: String {
return components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
}
}
|
//
// CitiesViewController.swift
// WeatherApp
//
// Created by Bartek Poskart on 29/05/2020.
// Copyright © 2020 Bartek Poskart. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
class CitiesViewController: UIViewController {
@UsesAutoLayout
private var tableView = UITableView()
@UsesAutoLayout
private var searchBar = UISearchBar()
private var disposeBag = DisposeBag()
private var viewModel: CitiesViewModel!
private var coordinator: WeatherTransitionable!
class func instantiate(with model: CitiesViewModel, coordinator: WeatherTransitionable) -> CitiesViewController {
let vc = CitiesViewController()
vc.viewModel = model
vc.coordinator = coordinator
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupLayout()
setupTableView()
setupBackButton()
}
}
private extension CitiesViewController {
func setupTableView() {
tableView.register(CityTableViewCell.nib(),
forCellReuseIdentifier: CityTableViewCell.identifier)
searchBar.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 70.0
tableView.backgroundColor = .veryLightPink
tableView.separatorStyle = .none
tableView.keyboardDismissMode = .onDrag
tableView.tableFooterView = UIView()
}
func setupView() {
view.backgroundColor = .white
view.addSubview(tableView)
view.addSubview(searchBar)
}
func setupLayout() {
let topPadding = UIApplication.shared.topPadding
NSLayoutConstraint.activate([
searchBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 42.0 + topPadding),
searchBar.leftAnchor.constraint(equalTo: view.leftAnchor),
searchBar.rightAnchor.constraint(equalTo: view.rightAnchor),
searchBar.heightAnchor.constraint(equalToConstant: 62.0),
tableView.topAnchor.constraint(equalTo: searchBar.bottomAnchor),
tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
func setupBackButton() {
let button = UIBarButtonItem(title: "Powrót",
style: .plain,
target: self,
action: #selector(goBack))
navigationItem.leftBarButtonItem = button
}
@objc
func goBack() {
coordinator.leave(true, completion: nil)
}
}
extension CitiesViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
LocationService.shared.stopUpdatingLocation()
coordinator.showWeather(for: viewModel.cities[indexPath.row])
}
}
extension CitiesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.cities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CityTableViewCell.identifier, for: indexPath) as? CityTableViewCell else {
return UITableViewCell()
}
cell.setup(with: viewModel.cities[indexPath.row])
return cell
}
}
extension CitiesViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
viewModel.filter(with: searchText)
tableView.reloadData()
}
}
|
//
// GetAccountDids.swift
// VitelityClient
//
// Created by Jorge Enrique Dominguez on 10/19/18.
// Copyright © 2018 sigmatric. All rights reserved.
//
import Foundation
public struct GetAccountDids {
public let dids: [AccountDidDTO]?
}
|
//
// ViewController.swift
// BitCoin
//
// Created by Abdelrahman on 3/3/20.
// Copyright © 2020 Abdelrahman. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var currencyPicker: UIPickerView!
@IBOutlet weak var bitcoinLabel: UILabel!
@IBOutlet weak var currencyLabel: UILabel!
@IBOutlet weak var coinView: UIView!
var coinManager = CoinManager()
override func viewDidLoad() {
super.viewDidLoad()
currencyPicker.delegate = self
coinManager.delegate = self
coinView.layer.cornerRadius = 40
coinView.layer.masksToBounds = true
}
}
//MARK: - UIPickerViewDelegate & UIPickerViewDataSource
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return coinManager.currencyArr.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return coinManager.currencyArr[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let currency = coinManager.currencyArr[row]
coinManager.getCoinPrice(for: currency)
currencyLabel.text = currency
}
}
//MARK: - CoinManagerDelegate
extension ViewController: CoinManagerDelegate{
func didFailWithError(_ error: Error) {
print(error)
}
func didUpdateCurrency(_ coinManager: CoinManager, coin: CoinData) {
DispatchQueue.main.async {
self.bitcoinLabel.text = String(format:"%.2f",coin.rate)
}
}
}
|
//
// NobalaViewController.swift
// Nobala
//
// Created by Abdelrahman Mohamed on 6/17/16.
// Copyright © 2016 Abdelrahman Mohamed. All rights reserved.
//
import UIKit
class NobalaViewController: UIViewController {
var url = NobalaClient.Constants.BaseURL
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.leftBarButtonItem = nil
self.navigationItem.hidesBackButton = true
}
@IBAction func newsButtonClicked(sender: AnyObject)
{
NobalaClient.sharedInstance().get10News((url + NobalaClient.Methods.get10News))
{
(success, error) in
print("btn10News")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//you can throw, catch, propogate, or manipulate errors
//when an operation fails, its useful to figure out what caused the error
//ex. reading data from file on disk
//ways it could fail: 1) file doesnt exist at specified path 2) file doesnt have read permission
//3) file not encoded in a compatible format
// ***** Representing and Throwing Errors *****
//ErrorType protocol - indicates that an implementing type can be used for error handling
//so errors are represented by values that conform to the ErrorType protocol
//enums are useful for modelling a group of related errors: ex)
enum VendingMachineError: ErrorType {
case InvalidSelection
case InsufficientFunds(coinsNeeded: Int)
case OutOfStock
}
//throwing error means something unexpected happen and normal execution cant continue
//use throw statement to throw an error as such:
//throw VendingMachineError.InsufficientFunds(coinsNeeded: 5)
// ***** Handling Errors *****
//when an error is thrown, surrounding code must be responsible for handling the error
//4 ways to handle error:
//1) propogate the error from function to code that calls the function
//2) assert that error will not occur
//3) handle error with do-catch statement
//4) handle error as an optional value
//use try (or try? or try!) before a piece of code that calls a function that can throw an error
//Method 1. Propogating Errors using throwing functions
struct Item {
var price: Int
var count: Int
}
class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 11)
]
var coinsDeposited = 0
func dispenseSnack(snack: String) {
print("Dispensing \(snack)")
}
//this function can throw an error of the enum type we defined above.
func vend(itemNamed name: String) throws {
guard var item = inventory[name] else {
throw VendingMachineError.InvalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.OutOfStock
}
guard item.price <= coinsDeposited else {
throw VendingMachineError.InsufficientFunds(coinsNeeded: item.price - coinsDeposited)
}
coinsDeposited -= item.price
--item.count
inventory[name] = item
dispenseSnack(name)
}
}
//to call the func vend:itemNamed which throws an error, we must call after the keyword try
//try vendingMachine.vend(itemNamed: snackName) -> this will propogate an error if one is thrown
//Method 2: Handling Errors Using do-catch
/*do {
try expression
statements
} catch pattern 1 {
statements
} catch pattern 2 where condition {
statements
}*/
//general formal of a do-catch sequence, in which the do block of code
//is where one would call a function that may throw an error, and if one is thrown
//the catch statements are used to match against specific error throws to handle the error
//SO: if error is thrown by a try funcCall, execution immediately transfers to
//catch block to handle the error
//if no error is thrown, remaining statements are executed in the do block
//Method 3: Converting Errors to Optionals
//use try? before a throwing function to return a nil
//ex) func someThrowingFunction() throws -> Int { ... }
//let x = try? someThrowingFunction() //if an error is thrown, x is assigned nil to express that error was thrown
//let y: Int?
//do {
//y = try someThrowingFunction() error thrown sends execution to catch, which will set y to nil
//} catch {
//y = nil
//}
// Method 4: Disable Error Propagation
//if we know FOR SURE that no error will be thrown, we can use try! to call an error throwing function
// ***** Specifying Cleanup Action *****
//defer keyword used before sequence of statements that must be executed just before
//execution leaves the current block
//defer blocks defer execution of statements until the current scope is exited
//ex)
/*func processFile(filename: String) throws {
if exists(filename) {
let file = open(filename)
defer {
close(file)
}
while let line = try file.readline() {
//
}
//close is called here cause were at the end of scope
}
}*/
|
//
// KeyboardViewController_Traits.swift
// Keyboard
//
// Created by Matt Zanchelli on 6/15/14.
// Copyright (c) 2014 Matt Zanchelli. All rights reserved.
//
import UIKit
// Because of some issue with the compiler right now, I must make this functions and not properties. Ugh.
extension KeyboardViewController {
/// Provides textual context to a custom keyboard.
func traits() -> UITextDocumentProxy {
return self.textDocumentProxy as! UITextDocumentProxy
}
/// The auto-capitalization style for the text object.
/// @discussion This property determines at what times the Shift key is automatically pressed, thereby making the typed character a capital letter. The default value for this property is @c UITextAutocapitalizationTypeSentences.
func autocapitalizationType() -> UITextAutocapitalizationType {
return self.traits().autocapitalizationType!
}
/// The auto-correction style for the text object.
/// @discussion This property determines whether auto-correction is enabled or disabled during typing. With auto-correction enabled, the text object tracks unknown words and suggests a more suitable replacement candidate to the user, replacing the typed text automatically unless the user explicitly overrides the action.
/// @discussion The default value for this property is @c UITextAutocorrectionTypeDefault, which for most input methods results in auto-correction being enabled.
func autocorrectionType() -> UITextAutocorrectionType {
return self.traits().autocorrectionType!
}
/// The spell-checking style for the text object.
/// @discussion This property determines whether spell-checking is enabled or disabled during typing. With spell-checking enabled, the text object generates red underlines for all misspelled words. If the user taps on a misspelled word, the text object presents the user with a list of possible corrections.
/// @discussion The default value for this property is @c UITextSpellCheckingTypeDefault, which enables spell-checking when auto-correction is also enabled. The value in this property supersedes the spell-checking setting set by the user in Settings > General > Keyboard.
func spellCheckingType() -> UITextSpellCheckingType {
return self.traits().spellCheckingType!
}
/// A Boolean value indicating whether the return key is automatically enabled when text is entered by the user.
/// @discussion The default value for this property is @c NO. If you set it to @c YES, the keyboard disables the return key when the text entry area contains no text. As soon as the user enters any text, the return key is automatically enabled.
func enablesReturnKeyAutomatically() -> Bool {
return self.traits().enablesReturnKeyAutomatically!
}
/// The appearance style of the keyboard that is associated with the text object.
/// This property lets you distinguish between the default text entry inside your application and text entry inside an alert panel. The default value for this property is @c UIKeyboardAppearanceDefault.
func keyboardAppearance() -> UIKeyboardAppearance {
return self.traits().keyboardAppearance!
}
/// The keyboard style associated with the text object.
/// @discussion Text objects can be targeted for specific types of input, such as plain text, email, numeric entry, and so on. The keyboard style identifies what keys are available on the keyboard and which ones appear by default. The default value for this property is @c UIKeyboardTypeDefault.
func keyboardType() -> UIKeyboardType {
return self.traits().keyboardType!
}
/// The contents of the “return” key.
/// Setting this property to a different key type changes the title of the key and typically results in the keyboard being dismissed when it is pressed. The default value for this property is @c UIReturnKeyDefault.
func returnKeyType() ->UIReturnKeyType {
return self.traits().returnKeyType!
}
}
|
//
// Config.swift
// MobileTestPR
//
// Created by Derek Bronston on 12/18/18.
// Copyright © 2018 Freshly. All rights reserved.
//
import Foundation
enum Strings: String {
case error = "Sorry, something went wrong."
}
enum Tags: Int {
case loadingTag = 2
}
enum URLS: String {
case login = "https://test.com/login_test.php"
case data = "https://test.com/data.php"
}
|
//
// WledApiResponse.swift
// WLED Swift
//
// Created by Wisse Hes on 26/09/2021.
//
import Foundation
struct WledApiResponse: Codable {
let state: WledState
}
struct WledState: Codable {
let on: Bool
let brightness: Float
let presetIndex: Int
let playlistIndex: Int
let udpn: WledUDPN
enum CodingKeys: String, CodingKey {
case on = "on"
case brightness = "bri"
case presetIndex = "ps"
case playlistIndex = "pl"
case udpn = "udpn"
}
}
struct WledUDPN: Codable {
let send: Bool
let receive: Bool
enum CodingKeys: String, CodingKey {
case send
case receive = "recv"
}
}
|
//
// ScaryBugTableViewController.swift
// TableViewDemo
//
// Created by VKS on 3/21/16.
// Copyright © 2016 VKS. All rights reserved.
//
import UIKit
class ScaryBugTableViewController: UITableViewController {
//var scaryBugs:[ScaryBug]!
var bugSections = [BugSection]()
@IBOutlet weak var bugTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//scaryBugs = ScaryBug.bugs()
self.navigationItem.title = "Scary Bugs"
self.navigationItem.rightBarButtonItem = editButtonItem()
setupBugs()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupBugs(){
bugSections.append(BugSection(howScary: .NotScary))
bugSections.append(BugSection(howScary: .ALittleScary))
bugSections.append(BugSection(howScary: .AverageScary))
bugSections.append(BugSection(howScary: .QuiteScary))
bugSections.append(BugSection(howScary: .Aiiiiieeeee))
let bugs = ScaryBug.bugs()
for bug in bugs{
let bugSection = bugSections[bug.howScary.rawValue]
bugSection.bugs.append(bug)
}
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: true)
if(editing){
self.bugTableView.setEditing(editing, animated: true)
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return bugSections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return bugSections[section].bugs.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return ScaryBug.scaryFactorToString(bugSections[section].howScary)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let scaryBug = bugSections[indexPath.section].bugs[indexPath.row]
cell.imageView?.image = scaryBug.image
cell.textLabel?.text = scaryBug.name
// Configure the cell...
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
bugSections[indexPath.section].bugs.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// MessageCell.swift
// GoodFeels
//
// Created by Edward Freeman on 12/21/15.
// Copyright © 2015 NinjaSudo LLC. All rights reserved.
//
import UIKit
class MessageCell: UITableViewCell {
@IBOutlet weak var messageLabel: UILabel!
}
|
//
// IntegrationTestCase.swift
//
//
// Created by Vladislav Fitc on 05/03/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class IntegrationTestCase: XCTestCase {
var client: SearchClient!
var index: Index!
let expectationTimeout: TimeInterval = 100
let retryCount: Int = 3
var retryableTests: [() throws -> Void] { return [] }
var allowFailure: Bool { return false }
/// Abstract base class for online test cases.
///
var indexNameSuffix: String? {
return nil
}
func uniquePrefix() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD_HH:mm:ss"
let dateString = dateFormatter.string(from: .init())
return "swift_\(dateString)_\(NSUserName().description)"
}
var environment: TestCredentials.Environment { .primary }
override func setUpWithError() throws {
try super.setUpWithError()
let fetchedCredentials = Result(catching: { try TestCredentials(environment: environment) }).mapError { XCTSkip("\($0)") }
let credentials = try fetchedCredentials.get()
client = SearchClient(appID: credentials.applicationID, apiKey: credentials.apiKey)
let indexNameSuffix = self.indexNameSuffix ?? name
let indexName = IndexName(stringLiteral: "\(uniquePrefix())_\(indexNameSuffix)")
index = client.index(withName: indexName)
try index.delete()
}
func testRetryable() throws {
for test in retryableTests {
for attemptCount in 1...retryCount {
do {
try test()
break
} catch let error where attemptCount == retryCount {
try XCTSkipIf(allowFailure)
throw Error.retryFailed(attemptCount: attemptCount, error: error)
} catch _ {
continue
}
}
}
}
override func tearDownWithError() throws {
try super.tearDownWithError()
if let index = index {
try index.delete()
}
}
}
extension IntegrationTestCase {
enum Error: Swift.Error {
case missingCredentials
case retryFailed(attemptCount: Int, error: Swift.Error)
}
}
|
//
// ViewController.swift
// PlayerDemo
//
// Created by ning on 16/10/26.
// Copyright © 2016年 songjk. All rights reserved.
//
import UIKit
import AVFoundation
import SnapKit
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let screenW = UIScreen.main.bounds.width
let screenH = UIScreen.main.bounds.height
class ViewController: UIViewController {
var topView : UIView!
var bottomView : UIView!
var downBtn : UIButton!
var progressSlider : UISlider!
var progress : UIProgressView!
var timeLable : UILabel!
var leftLable : UILabel!
var previousBtn : UIButton!
var startBtn : UIButton!
var nextBtn : UIButton!
var player : AVPlayer!
var playerItem : AVPlayerItem!
var timer : Timer!
var alphaTimer : Timer!
// override var supportedInterfaceOrientations: UIInterfaceOrientationMask
override func viewDidLoad() {
super.viewDidLoad()
//横屏
createPlayer()
createTopViewAndBottomView()
}
override func viewWillAppear(_ animated: Bool) {
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
override func viewDidDisappear(_ animated: Bool) {
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
//自定义播放界面
fileprivate func createTopViewAndBottomView() {
self.view.backgroundColor = UIColor.black
topView = UIView.init()
topView.backgroundColor = UIColor.black
topView.alpha = 0.5
self.view.addSubview(topView)
downBtn = UIButton.init(type: .custom)
downBtn.setTitle("完成", for: .normal)
downBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
downBtn.addTarget(self, action: #selector(downBtnClick), for: .touchUpInside)
topView.addSubview(downBtn)
progressSlider = UISlider.init()
progressSlider.isContinuous = false
progressSlider.addTarget(self, action: #selector(progressSliderValueChange), for: .valueChanged)
progress = UIProgressView.init()
progress.trackTintColor = UIColor.white
progress.progressTintColor = UIColor.gray
topView.addSubview(progress)
topView.addSubview(progressSlider)
timeLable = UILabel();
timeLable.font = UIFont.systemFont(ofSize: 13.0)
topView.addSubview(timeLable)
leftLable = UILabel();
leftLable.font = UIFont.systemFont(ofSize: 13.0)
topView.addSubview(leftLable)
bottomView = UIView.init()
bottomView.backgroundColor = UIColor.black
bottomView.alpha = 0.5
previousBtn = UIButton.init(type: .custom)
previousBtn.setImage(UIImage.init(named: "idx1"), for: .normal)
startBtn = UIButton.init(type: .custom)
startBtn.setImage(UIImage.init(named: "idx1"), for: .normal)
startBtn.backgroundColor = UIColor.red
startBtn.addTarget(self, action: #selector(startAndParuse(sender:)), for: .touchUpInside)
nextBtn = UIButton.init(type: .custom)
nextBtn.setImage(UIImage.init(named: "idx1"), for: .normal)
nextBtn.addTarget(self, action: #selector(nextVideo), for: .touchUpInside)
bottomView.addSubview(previousBtn)
bottomView.addSubview(startBtn)
bottomView.addSubview(nextBtn)
self.view.addSubview(bottomView)
timeLable.backgroundColor = UIColor.red
leftLable.backgroundColor = UIColor.red
contentMasnory()
self.view.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapView))
self.view.addGestureRecognizer(tap)
self.perform(#selector(alphaChange), with: self, afterDelay: 4)
let swipe = UISwipeGestureRecognizer.init(target: self, action: #selector(swiptUp))
swipe.direction = .up
self.view.addGestureRecognizer(swipe)
// alphaTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(alphaChange), userInfo: nil, repeats: <#T##Bool#>)
}
//创建player
fileprivate func createPlayer() {
playerItem = AVPlayerItem.init(url: NSURL.init(string: "http://krtv.qiniudn.com/150522nextapp") as! URL)
playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
player = AVPlayer.init(playerItem: playerItem)
let playerLayer = AVPlayerLayer.init(player: player)
playerLayer.frame = CGRect.init(x: 0, y: 0, width: screenW, height: screenH)
playerLayer.videoGravity = AVLayerVideoGravityResize
self.view.layer.addSublayer(playerLayer)
player.play()
addTimer()
}
//添加约束
func contentMasnory() {
topView.snp.makeConstraints { (make) in
make.left.equalTo(0)
make.trailing.equalTo(0)
make.top.equalTo(0)
make.height.equalTo(50)
}
downBtn.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(10)
make.height.equalTo(30)
make.width.equalTo(40)
}
timeLable.snp.makeConstraints { (make) in
make.left.equalTo(downBtn.snp.right).offset(10)
make.top.equalTo(downBtn)
make.height.equalTo(downBtn)
make.width.equalTo(downBtn)
}
progressSlider.snp.makeConstraints { (make) in
make.left.equalTo(timeLable.snp.right).offset(10)
make.top.equalTo(timeLable)
make.height.equalTo(timeLable)
make.trailing.equalTo(-100)
}
progress.snp.makeConstraints { (make) in
make.centerY.equalTo(progressSlider.snp.centerY).offset(0.5)
make.left.equalTo(progressSlider.snp.left).offset(2)
make.trailing.equalTo(progressSlider.snp.trailing).offset(-2)
make.height.equalTo(1.5)
}
leftLable.snp.makeConstraints { (make) in
make.left.equalTo(progressSlider.snp.right).offset(10)
make.top.equalTo(10)
make.width.equalTo(50)
make.height.equalTo(30)
}
bottomView.snp.makeConstraints { (make) in
make.left.equalTo(0)
make.bottom.equalTo(self.view.snp.bottom)
make.trailing.equalTo(0)
make.height.equalTo(50)
}
startBtn.snp.makeConstraints { (make) in
make.centerX.equalTo(bottomView)
make.centerY.equalTo(bottomView)
make.height.equalTo(40)
make.width.equalTo(30)
}
previousBtn.snp.makeConstraints { (make) in
make.trailing.equalTo(startBtn.snp.leading).offset(-30)
make.width.equalTo(30)
make.height.equalTo(30)
make.top.equalTo(10)
}
nextBtn.snp.makeConstraints { (make) in
make.left.equalTo(startBtn.snp.right).offset(30)
make.width.equalTo(previousBtn)
make.height.equalTo(previousBtn)
make.top.equalTo(10)
}
}
//开始播放和暂停播放
func startAndParuse(sender:UIButton) {
if sender.isSelected {
player.play()
addTimer()
sender.isSelected = false
}else{
player.pause()
removeTimer()
sender.isSelected = true
}
}
//下一曲,这里应该重新创建 AVPlayerItem
func nextVideo() {
// player = nil
player.pause()
removeTimer()
playerItem.removeObserver(self, forKeyPath: "loadedTimeRanges", context: nil)
playerItem = nil
// player = nil
let playerI = AVPlayerItem.init(url: NSURL.init(string: "http://wvideo.spriteapp.cn/video/2016/0328/56f8ec01d9bfe_wpd.mp4") as! URL)
//
player.replaceCurrentItem(with: playerI)
// let play = AVPlayer.init(playerItem: playerI)
// player = play
playerItem = playerI
playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
player.play()
addTimer()
}
func addTimer() {
if timer == nil {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerProgress), userInfo: nil, repeats: true)
}
}
func removeTimer() {
if timer != nil {
timer.invalidate()
timer = nil;
}
}
func downBtnClick() {
removeTimer()
self.dismiss(animated: true, completion: nil)
}
func tapView() {
if topView.alpha == 0.5 {
UIView.animate(withDuration: 0.5, animations: {
self.topView.alpha = 0
self.bottomView.alpha = 0
})
}else{
UIView.animate(withDuration: 0.5, animations: {
self.topView.alpha = 0.5
self.bottomView.alpha = 0.5
// self.perform(#selector(self.alphaChange), with: nil, afterDelay: 4)
})
}
}
func swiptUp() {
let currentBrigt = UIScreen.main.brightness
let changeBrigt = currentBrigt + 5;
UIScreen.main.brightness = changeBrigt
}
func alphaChange() {
if topView.alpha == 0.5 {
UIView.animate(withDuration: 0.5, animations: {
self.topView.alpha = 0
self.bottomView.alpha = 0
})
}
}
func progressSliderValueChange() {
// 拖动改变视频播放进度
if player.status == .readyToPlay {
let total = Float(playerItem.duration.value/Int64(playerItem.duration.timescale))
let dragedSeconds = floorf(total * progressSlider.value)
let dragedCMTime = CMTime.init(value: CMTimeValue(dragedSeconds), timescale: 1)
player.pause()
removeTimer()
player.seek(to: dragedCMTime, completionHandler: { (finish) in
if finish {
self.player.play()
self.addTimer()
}
})
}
}
// 观察者模式 进行进度条的改变
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "loadedTimeRanges" {
// let timeinterval = self.availableDuration()//缓冲速度
let duration = playerItem.duration
let total = CMTimeGetSeconds(duration)
progress.setProgress(Float(total), animated: false)
}
}
func availableDuration() -> TimeInterval{
let loadedTimeRanges = player.currentItem?.loadedTimeRanges
let timeRange = loadedTimeRanges?.first?.timeRangeValue as CMTimeRange?
let startSeconds = CMTimeGetSeconds(timeRange!.start)
let durationSeconds = CMTimeGetSeconds(timeRange!.duration)
let result = (startSeconds + durationSeconds)
return result
}
//计算时间的方法
func timerProgress() {
if playerItem.duration.timescale != 0 {
progressSlider.maximumValue = 1.0
let total = Float(playerItem.duration.value/Int64(playerItem.duration.timescale))
progressSlider.value = Float(CMTimeGetSeconds(playerItem.currentTime()))/total
let promin = NSInteger(CMTimeGetSeconds(playerItem.currentTime()))/60//当前秒
let prosec = NSInteger(CMTimeGetSeconds(playerItem.currentTime()))%60//当前分
let durmin = NSInteger(total)/60
let dursec = NSInteger(total)%60
let leftmin = durmin - promin
let leftsec = dursec - prosec
timeLable.text = NSString.init(format: "%02ld:%02ld", promin,prosec,durmin,dursec) as String
leftLable.text = NSString.init(format: "-%02ld:%02ld", leftmin,leftsec) as String
}
}
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.
}
*/
}
|
//
// MessagesInteractorTests.swift
// CleanSwiftSampleTests
//
// Created by Okhan Okbay on 25.10.2020.
//
@testable import CleanSwiftSample
import XCTest
class MessagesInteractorTests: XCTestCase {
var sut: MessagesInteractor!
var mockDataStore: MockMessagesDataStore!
var mockWorker: MockMessagesWorker!
var mockPresenter: MockPresenter!
override func setUpWithError() throws {
mockDataStore = MockMessagesDataStore()
mockWorker = MockMessagesWorker()
mockPresenter = MockPresenter()
sut = MessagesInteractor(dataStore: mockDataStore,
worker: mockWorker,
presenter: mockPresenter)
}
}
// MARK: setupInitials(_:) tests
extension MessagesInteractorTests {
func test_WhenSetupInitialsCalled_ThenPresentInitialsCalled() {
// given
let request = MessagesViewInitials.Request()
let username = "TestUsername"
// when
mockDataStore.username = username
sut.setupInitials(request: request)
// then
XCTAssertEqual(mockPresenter.presentInitialsCallCount, 1, "Present initials is not called 1 time")
XCTAssertEqual(mockPresenter.presentInitialsReceivedResponse?.title, username, "Title is not as expected")
}
}
// MARK: fetchMessages(_:) tests
extension MessagesInteractorTests {
func test_WhenFetchMessagesCalledAndReceivesSuccessResponse_ThenPresentMessagesCalled() {
assert_WhenFetchMessagesCalled_ThenPresentMessagesCalled(isSuccessResponse: true)
}
func test_WhenFetchMessagesCalledAndReceivesFailureResponse_ThenPresentMessagesCalled() {
assert_WhenFetchMessagesCalled_ThenPresentMessagesCalled(isSuccessResponse: false)
}
func assert_WhenFetchMessagesCalled_ThenPresentMessagesCalled(isSuccessResponse: Bool, file: StaticString = #file, line: UInt = #line) {
// given
let request = FetchMessages.Request()
var expectedInnerValue: FetchMessages.Response.InnerValue
if isSuccessResponse {
let wrapper: MessagesWrapper = TestHelper.loadJSONFromFile(name: TestHelper.stubMessagesResponseFileName)
expectedInnerValue = .success(wrapper.messages)
} else {
expectedInnerValue = .failure("Server error")
}
// when
mockWorker.shouldReturnSuccess = isSuccessResponse
sut.fetchMessages(request: request)
// then
XCTAssertEqual(mockPresenter.presentMessagesCallCount, 1, "Present messages is not called 1 time")
XCTAssertEqual(mockPresenter.presentMessagesReceivedResponse?.innerValue, expectedInnerValue, "Inner value is not as expected")
}
}
// MARK: sendMessage(_:) tests
extension MessagesInteractorTests {
func test_WhenSendMessageCalledWithEmptyText_ThenPresentNewMessageNOTCalled() {
// given
let request = NewMessage.Request(text: nil)
// when
sut.sendMessage(request: request)
// then
XCTAssertEqual(mockPresenter.presentNewMessageCallCount, 0, "Present new message is called at least once")
XCTAssertNil(mockPresenter.presentNewMessageReceivedResponse, "New message is not nil")
}
func test_WhenSendMessageCalledeWithNONEmptyText_ThenPresentNewMessageCalled() {
// given
let message = "New message text"
let request = NewMessage.Request(text: message)
let username = "TestUsername"
// when
mockDataStore.username = username
sut.sendMessage(request: request)
// then
XCTAssertEqual(mockPresenter.presentNewMessageCallCount, 1, "Present new message is not called 1 time")
XCTAssertEqual(mockPresenter.presentNewMessageReceivedResponse?.message, message, "Message is not as expected")
XCTAssertEqual(mockPresenter.presentNewMessageReceivedResponse?.username, username, "Username is not as expected")
}
}
|
//
// Extension.swift
// iosApp
//
// Created by Rushikesh on 29/07/21.
// Copyright © 2021 orgName. All rights reserved.
//
import Foundation
import UIKit
extension ArticleListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let articleData = articleList[indexPath.row]
let desVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "DesriptionViewController") as! DesriptionViewController
desVC.titleString = articleData.title ?? ""
desVC.desriptionString = articleData.abstract ?? ""
desVC.articleUrl = articleData.url ?? ""
desVC.articleImageUrl = articleList[indexPath.row].media?[0].MediaMetadata?[0].url ?? ""
self.navigationController?.pushViewController(desVC, animated: true)
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
extension ArticleListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articleList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ArticleTableViewCell
let imageUrl = articleList[indexPath.row].media?[0].MediaMetadata?[0].url
let artcileData = articleList[indexPath.row]
cell.articleTitleLbl.text = artcileData.title
cell.articleAuuthorLabel.text = artcileData.byline
api.getImage(url: imageUrl ?? "", success: { image in
DispatchQueue.main.async {
cell.articleImageView.image = image
cell.setNeedsLayout()
}
}, failure: { error in
print(error?.description() ?? "")
})
cell.articleImageView.layer.cornerRadius = cell.articleImageView.frame.width/2.0
cell.articleImageView.layer.masksToBounds = true
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 130
}
}
extension UIImageView{
func round(){
self.layer.cornerRadius = self.frame.width/2.0
self.layer.masksToBounds = true
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.