text stringlengths 8 1.32M |
|---|
//
// EventViewController.swift
// ClubApp
//
// Created by intellye labs on 13/07/17.
// Copyright © 2017 intellye labs. All rights reserved.
//
import UIKit
import FSCalendar
import SVProgressHUD
import SDWebImage
class EventViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,FSCalendarDataSource, FSCalendarDelegate, UIGestureRecognizerDelegate,EventRespo {
let eventparsor : EventParsor = EventParsor()
var event : [Event] = []
var events_info = NSArray()
var event_list = NSArray()
var date_array = NSArray()
var image_array = NSArray()
var Event_id = NSArray()
var Event_type_id=NSArray()
var event_date=NSArray()
var event_description=NSArray()
var event_icon=NSArray()
var event_time=NSArray()
var event_title=NSArray()
var event_type_name=NSArray()
var event_venue=NSArray()
var date = ["one","two","three","four","five","six"]
// @IBOutlet weak var heightLayout: NSLayoutConstraint!
@IBAction func sidemenu(_ sender: Any) {
sideMenuViewController?._presentLeftMenuViewController()
}
@IBOutlet weak var table_view: UITableView!
// @IBOutlet weak var calendar: FSCalendar!
fileprivate lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
self.eventparsor.delegate=self
ShowProgress()
eventparsor.eventCheck(userid: "1")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Event_id.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell=tableView.dequeueReusableCell(withIdentifier: "cell_events",for : indexPath) as! EventsViewCell
cell.heading.text=event_title[indexPath.row] as? String
cell.event_description.text=event_description[indexPath.row] as? String
let Image_Url=event_icon[indexPath.row]
cell.event_image.sd_setImage(with: URL(string: Image_Url as! String), placeholderImage: UIImage(named: "avatar"))
var date = event_date[indexPath.row]
print(date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
var s = dateFormatter.date(from:date as! String)
let calendar = Calendar.current
let day = calendar.component(.day, from: s!)
let month = calendar.component(.month, from: s!)
let years = calendar.component(.year, from: s!)
var typeofevent=Event_type_id[indexPath.row] as? String
if(typeofevent == "1")
{
cell.cell_view.backgroundColor = UIColor.red
}
if(typeofevent == "2")
{
cell.cell_view.backgroundColor = UIColor.blue
}
if(typeofevent == "3")
{
cell.cell_view.backgroundColor = UIColor.green
}
cell.date_text.text = String(day)
cell.weak_text.text = String(years)
print(day)
print(years)
return (cell)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = indexPath.row
print("Row: \(row)")
var eid = Event_id[row] as! String
var typeid = Event_type_id[row] as! String
print("eid: \(typeid)")
if(typeid == "1")
{
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let VC_2 = storyBoard.instantiateViewController(withIdentifier: "eventdetails_view") as! EventDetailViewController
VC_2.eventids = eid as! String
self.present(VC_2, animated: true, completion: nil)
}
if(typeid == "2")
{
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let VC_2 = storyBoard.instantiateViewController(withIdentifier: "meeting_view_controller") as! MettingViewController
VC_2.eventids = eid as! String
self.present(VC_2, animated: true, completion: nil)
}
else
{
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let VC_2 = storyBoard.instantiateViewController(withIdentifier: "eventdetails_view") as! EventDetailViewController
VC_2.eventids = eid as! String
self.present(VC_2, animated: true, completion: nil)
}
}
//
// func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//
// let cell=tableView.dequeueReusableCell(withIdentifier: "text_cell",for : indexPath) as! EventsViewCell
//
//
// let even = event[indexPath.section]
// let details = even.details[indexPath.row]
// cell.heading.text=details.tittle
// return cell
// }
// func numberOfSections(in tableView: UITableView) -> Int {
// print("conunt in sections", event.count)
// return event.count
// }
// func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// let events=event[section]
// print("conunt", events.details.count)
// return events.details.count
// }
// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// let eve=event[section]
// return eve.date
// }
func eventResponceLister(response: NSDictionary) {
if(response.value(forKey:"error") as! Bool?)!
{
cancelProgress()
print("error is true")
}
else{
events_info=response.value(forKey: "events_info") as! NSArray
print("events_info",events_info)
Event_id=events_info.value(forKey: "Event_id") as! NSArray
Event_type_id=events_info.value(forKey: "Event_type_id") as! NSArray
event_date=events_info.value(forKey: "event_date") as! NSArray
event_description=events_info.value(forKey: "event_description") as! NSArray
event_icon=events_info.value(forKey: "event_icon") as! NSArray
event_time=events_info.value(forKey: "event_time") as! NSArray
event_title=events_info.value(forKey: "event_title") as! NSArray
event_type_name=events_info.value(forKey: "event_type_name") as! NSArray
event_venue=events_info.value(forKey: "event_venue") as! NSArray
table_view.reloadData()
}
cancelProgress()
}
func ShowProgress() {
SVProgressHUD.show(withStatus: "Loading.")
SVProgressHUD.setBackgroundColor(UIColor .white)
SVProgressHUD.show()
}
func cancelProgress() {
SVProgressHUD.dismiss()
}
}
|
//
// ViewController.swift
// ARSolar
//
// Created by Shane Harrigan on 17/05/2020.
// Copyright © 2020 Shane Harrigan. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet var sceneView: ARSCNView!
@IBOutlet weak var picker: UIPickerView!
var bodyModelArr : [BodyModel] = [BodyModel]()
var node : SCNNode = SCNNode()
var pickerData : [String] = [String]()
var selectedBody : Int = 0
func populateBodyModelArray() {
let solModel = BodyModel(bodyName: "Sol", imageFile: "art.scnassets/sun.jpg", radius: 0.6)
let earthModel = BodyModel(bodyName: "Earth", imageFile: "art.scnassets/earth.jpg", radius: 0.2)
let moonModel = BodyModel(bodyName: "Moon", imageFile: "art.scnassets/moon.jpg", radius: 0.1)
self.bodyModelArr.append(solModel)
self.bodyModelArr.append(earthModel)
self.bodyModelArr.append(moonModel)
}
func getBodyNames() -> [String] {
var arr : [String] = []
for s in self.bodyModelArr{
arr.append(s.bodyName)
}
return arr
}
func setModelTexture(){
let sphere = SCNSphere(radius: CGFloat(bodyModelArr[selectedBody].radius))
let material = SCNMaterial()
material.diffuse.contents = UIImage(named: bodyModelArr[selectedBody].imageFile)
sphere.materials = [material]
self.node.geometry = sphere
sceneView.scene.rootNode.addChildNode(self.node)
sceneView.autoenablesDefaultLighting = true
}
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
populateBodyModelArray()
self.picker.delegate = self
self.picker.dataSource = self
pickerData = getBodyNames()
self.node.position = SCNVector3(0, 0.1, -2)
setModelTexture()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
var configuration : ARConfiguration? = AROrientationTrackingConfiguration()
if ARWorldTrackingConfiguration.isSupported {
// Create a session configuration
configuration = ARWorldTrackingConfiguration()
}
// Run the view's session
sceneView.session.run(configuration!)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectedBody = row
self.setModelTexture()
}
}
|
//
// ParkingAnnotation.swift
// ParkingFinder
//
// Created by Mark Lagae on 2/26/17.
// Copyright © 2017 Mark Lagae. All rights reserved.
//
import MapKit
class ParkingAnnotation: NSObject, MKAnnotation {
let json: [String: AnyObject]
var subtitle: String?
init(json: [String: AnyObject]) {
self.json = json
super.init()
}
var title: String? {
return json["location_name"] as? String
}
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: Double(json["lat"] as! NSNumber), longitude: Double(json["lng"] as! NSNumber))
}
}
|
//
// PhotoViewController.swift
// SwiftP
//
// Created by Rushikesh Kulkarni on 14/06/17.
// Copyright © 2017 simplicity. All rights reserved.
//
import UIKit
class PhotoViewController: UIViewController, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var userPhotoImageView: UIImageView!
var pickerController = UIImagePickerController()
var imageView = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
// let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(_:)))
let imageTapGesture = UITapGestureRecognizer(target: self, action: #selector(tapUserPhoto(_:)))
imageTapGesture.delegate = self
userPhotoImageView.addGestureRecognizer(imageTapGesture)
imageTapGesture.numberOfTapsRequired = 1
userPhotoImageView.isUserInteractionEnabled = true
pickerController.delegate = self
}
func tapUserPhoto(_ sender: UITapGestureRecognizer){
let alertViewController = UIAlertController(title: "", message: "Choose your option", preferredStyle: .actionSheet)
let camera = UIAlertAction(title: "Camera", style: .default, handler: { (alert) in
self.openCamera()
})
let gallery = UIAlertAction(title: "Gallery", style: .default) { (alert) in
self.openGallary()
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (alert) in
}
alertViewController.addAction(camera)
alertViewController.addAction(gallery)
alertViewController.addAction(cancel)
self.present(alertViewController, animated: true, completion: nil)
}
func openCamera() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
pickerController.delegate = self
self.pickerController.sourceType = UIImagePickerControllerSourceType.camera
pickerController.allowsEditing = true
self .present(self.pickerController, animated: true, completion: nil)
}
else {
let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
alertWarning.show()
}
}
func openGallary() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
pickerController.allowsEditing = true
self.present(pickerController, animated: true, completion: nil)
}
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imageView = info[UIImagePickerControllerEditedImage] as! UIImage
userPhotoImageView.contentMode = .scaleAspectFill
userPhotoImageView.image = imageView
dismiss(animated:true, completion: nil)
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("Cancel")
}
}
|
//
// FriendCollection.swift
// weatherAppGB
//
// Created by Андрей Коноплёв on 01.04.2020.
// Copyright © 2020 Андрей Коноплёв. All rights reserved.
//
import UIKit
class FriendCollection: UICollectionViewController {
var photos = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
photos.count
}
override func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "friendCollectionCell", for: indexPath) as! FriendsCollectionCell
cell.newPic.image = UIImage(named: photos[indexPath.row])
return cell
}
}
extension FriendCollection: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - 50) / 2
return CGSize(width: cellWidth, height: cellWidth)
}
}
|
import UIKit
import MapKit
import RealmSwift
import MediaPlayer
import Foundation
class ViewController: UIViewController, MKMapViewDelegate{
@IBOutlet var mapView: MKMapView!
@IBOutlet weak var uiSwitch: UISwitch!
var userAnnotationImage: UIImage?//アノテーション画像
var userAnnotation: UserAnnotation?// アノテーションインスタンス
var placeAnnotation = PlaceAnnotation()//アノテーションインスタンス
var polyline: MKPolyline?
var isZooming: Bool?
var isBlockingAutoZoom: Bool?
var didInitialZoom: Bool?//
var nowLocation: CLLocation?
//アノテーションに記載する情報
var name: String = ""
var album: String = ""
var artist: String = ""
var artwork = Data()
var lati: String = ""
var longi: String = ""
var date: String = ""
//アノテーション(ピン)の作成
var doubleLati: Double = 0.0
var doubleLongi: Double = 0.0
//位置情報サービスを司るシングルトン
var sharedInstance:LocationService = LocationService.sharedInstance
//シングルトン呼び出し
let player = MusicService().player
override func viewDidLoad() {
super.viewDidLoad()
//精度と鮮度のフィルタは常時ON
sharedInstance.useFilter = true
//自身をmapViewのデリゲートに設定
self.mapView.delegate = self
//自分の位置に青丸を使う
self.mapView.showsUserLocation = true
//アノテーション画像に自前の赤丸を設定
//self.userAnnotationImage = UIImage(named: "user_position_ball")!
//初期位置のズームをした後かどうかのフラグを設定
self.didInitialZoom = false
//ロケーションのアップデートを監視し,適宜updateMapを発動
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateMap(_:)), name: Notification.Name(rawValue:"didUpdateLocation"), object: nil)
//位置情報取得の許可を監視し,適宜アラートを発動
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.showTurnOnLocationServiceAlert(_:)), name: Notification.Name(rawValue:"showTurnOnLocationServiceAlert"), object: nil)
}
//この画面に入るたび,必ず一発目の処理として行う
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
//音楽履歴にピンを降らす
self.dropLocationMusicPin()
//今の位置に画面をもっていく
nowLocation = sharedInstance.locationManager.location
if nowLocation != nil{
zoomTo(location: nowLocation!)
self.didInitialZoom = false
}
if sharedInstance.useTracking == true{//スイッチONの時
uiSwitch.setOn(true, animated: false)
}else{//スイッチOFFの時
uiSwitch.setOn(false, animated: false)
}
}
//マップにピンを立てる
func dropPin(at location: CLLocation) {
//初期位置(0,0)でないとき
if location.coordinate.latitude != 0 && location.coordinate.longitude != 0 {
let annotation = placeAnnotation
annotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let lati = location.coordinate.latitude
let longi = location.coordinate.longitude
let date = location.timestamp.description
annotation.title = "songname"
annotation.subtitle = "artist"+"\n"+date+"\n"+"\(lati),\(longi)"
self.mapView.addAnnotation(annotation)
}
}
//realmLocationMusic内の情報をもとにピンをマップ上に立てる
func dropLocationMusicPin(){
let realmLocationMusic = try! Realm()
let allDataArray = Array(realmLocationMusic.objects(LocationMusic.self))
var annotationArray = [MKAnnotation]()
//すべての要素でピンの作成,マップ追加
for row in allDataArray {
let annotation = PlaceAnnotation()
//アノテーションに記載する情報
name = row.name
album = row.album
artist = row.artist
artwork = row.artwork
lati = row.latitude
longi = row.longitude
date = row.Date
doubleLati = atof(lati)
doubleLongi = atof(longi)
//アノテーションの詳細
annotation.title = name
annotation.subtitle = artist+"\n"+date+"\n"+"\(String(describing: lati)),\(String(describing: longi))"+"あばば"+album+"あばば"+artist
annotation.coordinate = CLLocationCoordinate2DMake(doubleLati, doubleLongi)
annotation.album = album
annotation.artist = artist
annotation.artwork = artwork
//配列にピンを追加
annotationArray.append(annotation)
}
//mapViewに配列のピンを適用
self.mapView.addAnnotations(annotationArray)
}
//位置情報取得の許可が下りなかったら,アラートを出す
@objc func showTurnOnLocationServiceAlert(_ notification: NSNotification){
let alert = UIAlertController(title: "Turn on Location Service", message: "To use this app, please turn on the location service from the Settings app.", preferredStyle: .alert)
//"setting"選択肢を作成
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
//"cancel"選択肢を作成
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil)
//アラートに"setting"の選択肢を追加
alert.addAction(settingsAction)
//アラートに"cancel"の選択肢を追加
alert.addAction(cancelAction)
//アラートを表示
present(alert, animated: true, completion: nil)
}
//通知内容を元に,マップを更新する
@objc func updateMap(_ notification: NSNotification){
//通知に含まれるuserInfo(辞書型)がnilでなかったら
if let userInfo = notification.userInfo{
//マップ上の線を更新し,伸ばす.
updatePolylines()
//さらに,userInfoが"location"キーに対する値をもつ時
if let newLocation = userInfo["location"] as? CLLocation{
if sharedInstance.useTracking == true{
//新しい位置へズームする.
zoomTo(location: newLocation)
}else{
//何もしない
}
}
}
}
//マップ上の線を更新し,伸ばす
func updatePolylines(){
//平面位置(x,y)の配列作成
var coordinateArray = [CLLocationCoordinate2D]()
//位置情報の配列の要素(平面位置,高さ,平面精度,高さ精度,時刻)から,
for loc in LocationService.sharedInstance.locationDataArray{
//平面位置(x,y)のみを抽出していく
coordinateArray.append(loc.coordinate)
}
//全部線消しまーす
self.clearPolyline()
//作った配列の要素(x,y)をなぞるような線を作りまーす
self.polyline = MKPolyline(coordinates: coordinateArray, count: coordinateArray.count)
//線をmapViewにプロパティとして追加
self.mapView.add(polyline! as MKOverlay)
}
//マップ上の線を消す
func clearPolyline(){
//線があるとき
if self.polyline != nil{
//線を消す
self.mapView.remove(self.polyline!)
//籍は残したいので,nilを入れとく
self.polyline = nil
}
}
//ある位置にズームする
func zoomTo(location: CLLocation){
//(初回)イニシャルズーム済みフラグがfalseなら
if self.didInitialZoom == false{
//ユーザ位置にズームし,イニシャルズーム済みフラグをtrueにする
let coordinate = location.coordinate
let region = MKCoordinateRegionMakeWithDistance(coordinate, 300, 300)
self.mapView.setRegion(region, animated: false)
//この間にregionWillChangeAnimatedが呼び出される
self.didInitialZoom = true
}
//(2回目以降)オートズームさせないフラグがfalseなら
if self.isBlockingAutoZoom == false{
//ズーム中フラグを立てる
self.isZooming = true
//マップの中心を現在地に合わせる
self.mapView.setCenter(location.coordinate, animated: true)
}
}
//MKMapViewのデリゲート
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polylineRenderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
polylineRenderer.strokeColor = UIColor(rgb:0x1b60fe)
polylineRenderer.alpha = 0.5
polylineRenderer.lineWidth = 5.0
return polylineRenderer
// }
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "annotationIdentifier"
var pinView = self.mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.canShowCallout = true
pinView?.animatesDrop = true
// pinのクラス名を取得(今回の場合は「CustomAnnotation」になります)
switch NSStringFromClass(type(of: annotation)).components(separatedBy:".").last! as String {
case "PlaceAnnotation":
// ( annotation as! PlaceAnnotation )をしないと
// CustomAnnotationクラスで定義した変数が取れないので注意!
if ( annotation as! PlaceAnnotation ).artist != nil {
}
default: break
}
}
else {
pinView?.annotation = annotation
}
//THIS IS THE GOOD BIT
let subtitleView = UILabel()
subtitleView.font = subtitleView.font.withSize(12)
subtitleView.numberOfLines = 3
subtitleView.text = annotation.subtitle??.components(separatedBy:"あばば")[0]
pinView!.detailCalloutAccessoryView = subtitleView
//左にアルバムのジャケットを表示する
let button = UIButton()
button.frame = CGRect(x:0,y:0,width:100,height:100)
var AW: UIImage
//annotationのartworkを保持できていない時
if annotation.artwork == nil{
// realmからジャケ写画像を検索
let realm = try! Realm()
let name = annotation.title
let album = annotation.subtitle??.components(separatedBy:"あばば")[1]
let artist = annotation.subtitle??.components(separatedBy:"あばば")[2]
// 曲名とアルバム名,アーティスト名でrealm内のオブジェクトを絞り込み(配列で返る)
//let predicate = NSPredicate(format: )
let results = realm.objects(LocationMusic.self).filter("name = %@", name)
var resultss = results.filter("album = %@", album)
var resultsss = resultss.filter("artist = %@", artist)
// ためしに検索結果のIDと名前を表示
for one in results {
print("\(one.name): \(one.album): \(one.artist)")
}
//検索結果の一番上のを画像に変換
let result1stImage = UIImage(data: (results.first?.artwork)!)
//その画像をジャケ写として使う
AW = result1stImage!
}else{//保持できている時
//保持している画像データを画像に変換し,ジャケ写にする
AW = UIImage(data: annotation.artwork!)!
}
button.setImage(AW, for: [])
pinView?.leftCalloutAccessoryView = button
//右ボタンをアノテーションビューに追加する。(きく)
let button2 = UIButton()
button2.frame = CGRect(x:0,y:0,width:40,height:40)
button2.setTitle("きく", for:[])
//ランダム色の画像を生成
let color = UIColor.random
button2.backgroundColor = color
button2.setTitleColor(UIColor.white, for:[])
pinView?.rightCalloutAccessoryView = button2
return pinView
}
//吹き出しアクササリー押下時の呼び出しメソッド
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if(control == view.leftCalloutAccessoryView) {
// ① UIAlertControllerクラスのインスタンスを生成
// タイトル, メッセージ, Alertのスタイルを指定する
// 第3引数のpreferredStyleでアラートの表示スタイルを指定する
let alert: UIAlertController = UIAlertController(title: (view.annotation?.title)!, message: "コメント:なし", preferredStyle: UIAlertControllerStyle.alert)
// ② Actionの設定
// Action初期化時にタイトル, スタイル, 押された時に実行されるハンドラを指定する
// 第3引数のUIAlertActionStyleでボタンのスタイルを指定する
// 削除ボタン
let deleatAction: UIAlertAction = UIAlertAction(title: "削除", style: UIAlertActionStyle.destructive, handler:{
// ボタンが押された時の処理を書く(クロージャ実装)
(action: UIAlertAction!) -> Void in
print("削除する")
})
// コメントボタン
let commentAction: UIAlertAction = UIAlertAction(title: "コメントをのこす", style: UIAlertActionStyle.default, handler:{
// ボタンが押された時の処理を書く(クロージャ実装)
(action: UIAlertAction!) -> Void in
print("コメントを残すよ")
})
// キャンセルボタン
let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.cancel, handler:{
// ボタンが押された時の処理を書く(クロージャ実装)
(action: UIAlertAction!) -> Void in
print("キャンセルだよ")
})
// ③ UIAlertControllerにActionを追加
alert.addAction(cancelAction)
alert.addAction(commentAction)
alert.addAction(deleatAction)
// ④ Alertを表示
present(alert, animated: true, completion: nil)
} else {
//右のボタンが押された場合はきく
let song = view.annotation?.title
let album = view.annotation?.subtitle??.components(separatedBy:"あばば")[1]
let artist = view.annotation?.subtitle??.components(separatedBy:"あばば")[2]
let query = Query.tripleFilter(song: song!!, albam: album!, artist: artist!)
if query != nil{
//一旦,realm内のSongクラスオブジェクトを全部削除
let realm = try! Realm()
let Songs = realm.objects(Song.self)
try! realm.write {
// Realmに保存されているSong型のオブジェクトを全て削除
realm.delete(Songs)
}
player.setQueue(with: query!)
player.play()
self.performSegue(withIdentifier: "fromMapToPlay", sender: nil)
}
}
}
func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {//2回目以降
//2回目以降のZoomToの分岐を誘発
self.isBlockingAutoZoom = false;
}
//トラッキング機能のオンオフを司るスイッチ
@IBAction func trackingSwitchAction(_ sender: UISwitch) {
if sender.isOn{//スイッチONの時
sharedInstance.useTracking = true
}else{//スイッチOFFの時
sharedInstance.useTracking = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// PushNotificationsAppDelegate.swift
// SimpleRIBApp
//
// Created by Prabin Kumar Datta on 31/08/21.
//
import UIKit
class PushNotificationsAppDelegate: AppDelegateType {
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error)
{
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
{
}
}
|
//
// FlightSRPResponseModelTests.swift
// FlightsSRPAssignmentTests
//
// Created by Satyam Sehgal on 10/06/19.
// Copyright © 2019 Satyam Sehgal. All rights reserved.
//
import XCTest
@testable import FlightsSRPAssignment
struct MockFlightSRPResponseModel {
struct FlightSRPResponseModel: Codable {
let airlineMap: AirlineMap
let airportMap: AirportMap
let flightsData: [FlightsData]
}
struct AirlineMap: Codable {
let sj, ai, g8, ja, indigo: String
enum CodingKeys: String, CodingKey {
case sj = "SJ"
case ai = "AI"
case g8 = "G8"
case ja = "JA"
case indigo = "IN"
}
}
struct AirportMap: Codable {
let DEL, MUM: String
}
struct FlightsData: Codable {
let originCode, destinationCode, takeoffTime, landingTime, price, airlineCode, classType: String
enum CodingKeys: String, CodingKey {
case originCode, destinationCode, takeoffTime, landingTime, price, airlineCode
case classType = "class"
}
}
}
class FlightSRPResponseModelTests: XCTestCase {
var responseModel: MockFlightSRPResponseModel.FlightSRPResponseModel?
override func setUp() {
}
override func tearDown() {
responseModel = nil
}
func testResponseModelIntialation() {
let json: [String: Any] = [
"airlineMap": [
"SJ": "Spicejet",
"AI": "Air India",
"G8": "Go Air",
"JA": "Jet Airways",
"IN": "Indigo"
],
"airportMap": [
"DEL": "New Delhi",
"MUM": "Mumbai"
],
"flightsData": [
[
"originCode": "DEL",
"destinationCode": "MUM",
"takeoffTime": "1396614600000",
"landingTime": "1396625400000",
"price": "11500",
"airlineCode": "G8",
"class": "Business"
],
]
]
var data: Data?
do {
data = try JSONSerialization.data(withJSONObject: json, options: [])
responseModel = try JSONDecoder().decode(MockFlightSRPResponseModel.FlightSRPResponseModel.self, from: data!)
} catch {
XCTFail("Fail to decode the model")
}
XCTAssertTrue(responseModel != nil, "Succesfully initialise the model")
}
}
|
//
// SectionsUIViewController.swift
// ELRDRG
//
// Created by Jonas Wehner on 30.08.20.
// Copyright © 2020 Martin Mangold. All rights reserved.
//
import UIKit
protocol MapSectionsProtocol {
func DroppedSectionToMap(location : CGPoint, section : Section)
}
class SectionsUIViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITableViewDragDelegate {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let itemprovider = NSItemProvider()
let dragitem = UIDragItem(itemProvider: itemprovider)
dragitem.localObject = sectionList[indexPath.row]
return [dragitem]
}
public var delegate : MapSectionsProtocol?
var mapView : UIView?
func tableView(_ tableView: UITableView, dragSessionDidEnd session: UIDragSession) {
if let view = mapView
{
let location = session.location(in: view)
if let del = self.delegate {
if let section = session.items[0].localObject as? Section
{
del.DroppedSectionToMap(location: location, section: section)
}
}
print("location: ")
print(location)
}
}
//Object properties
var sectionList : [Section] = []
//UI Refs
@IBOutlet weak var table: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
sectionList = SectionHandler().getSections()
return sectionList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.table.dequeueReusableCell(withIdentifier: "MapSectionTVC") as! MapSectionTVC
cell.setSection(section: sectionList[indexPath.row])
return cell
}
override func viewDidAppear(_ animated: Bool) {
self.table.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.table.dataSource = self
self.table.delegate = self
self.table.dragDelegate = self
self.table.dragInteractionEnabled = true
self.table.reloadData()
}
required init?(coder: NSCoder, mapView : UIView) {
self.mapView = mapView
super.init(coder: coder)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// GFItemInfoVC.swift
// GitHub_Followers
//
// Created by Maxim Granchenko on 06.05.2020.
// Copyright © 2020 Maxim Granchenko. All rights reserved.
//
import UIKit
class GFItemInfoVC: UIViewController {
public let vStackView = UIStackView()
public let itemInfoViewLeft = GFItemInfoView()
public let itemInfoViewRight = GFItemInfoView()
public let actionButton = GFButton()
public var user: User!
override func viewDidLoad() {
super.viewDidLoad()
layoutUI()
configureBackgroundView()
configureStackView()
configureActionButton()
}
init(user: User) {
super.init(nibName: nil, bundle: nil)
self.user = user
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureBackgroundView() {
view.layer.cornerRadius = 18
view.backgroundColor = .secondarySystemBackground
}
private func configureActionButton() {
actionButton.addTarget(self, action: #selector(handleActionButton), for: .touchUpInside)
}
@objc func handleActionButton() {}
private func layoutUI() {
view.addSubviews(vStackView, actionButton)
vStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
vStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
vStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
vStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
vStackView.heightAnchor.constraint(equalToConstant: 50),
actionButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
actionButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
actionButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
actionButton.heightAnchor.constraint(equalToConstant: 44)
])
}
private func configureStackView() {
vStackView.addArrangedSubview(itemInfoViewLeft)
vStackView.addArrangedSubview(itemInfoViewRight)
vStackView.distribution = .equalSpacing
vStackView.axis = .horizontal
}
}
|
//
// CollectionFooterView.swift
// test
//
// Created by 大杉网络 on 2019/8/6.
// Copyright © 2019 大杉网络. All rights reserved.
//
import UIKit
class CollectionFooterView: UICollectionReusableView {
var view = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
self.view = UIView.init(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height:self.frame.size.height ))
self.addSubview(view)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// SectionTwoTableViewCell.swift
// MovieMemo
//
// Created by 신미지 on 2021/07/19.
//
import UIKit
class SectionTwoTableViewCell: UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var topRated = [Movie]()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionView.delegate = self
collectionView.dataSource = self
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.register(UINib(nibName: "SectionTwoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "SectionTwoCollectionViewCell")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func config(with movie: [Movie]) {
self.topRated = movie
collectionView.reloadData()
}
}
extension SectionTwoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return topRated.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SectionTwoCollectionViewCell", for: indexPath) as! SectionTwoCollectionViewCell
if let image = topRated[indexPath.item].posterPath {
cell.posterImageView.kf.setImage(with: URL(string: "https://image.tmdb.org/t/p/w500\(image)"))
} else {
print("이미지가 없습니다.")
}
// cell.backgroundColor = .purple
// cell.posterImageView.image = UIImage(named: "harrypotter")
return cell
}
}
extension SectionTwoTableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// let width = collectionView.safeAreaLayoutGuide.layoutFrame.width
// let height = collectionView.safeAreaLayoutGuide.layoutFrame.height
return CGSize(width: collectionView.frame.size.width / 3, height: 350)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
}
|
//
// Network .swift
// Rate Compare App
//
// Created by Jojo Destreza on 9/11/19.
// Copyright © 2019 Jojo Destreza. All rights reserved.
//
import UIKit
struct RequestStatusList2<T: Codable> : Codable {
let status: Int
let message: String
let data : [T]?
}
struct RequestStatusList<T: Codable> : Codable {
let status: Int
let message: String
let data : T?
let dataArray : [T]?
}
struct RequestStatus : Codable {
let status: Int
let message: String
}
struct StatusList {
let status: Int
let title: String
let message: String
let tag : Int?
}
class NetworkService<T:Codable> : NSObject {
var hasInternet : Bool = false
override init() {
self.hasInternet = true
}
func networkRequest(_ param : [String: Any],jsonUrlString: String,completionHandler: @escaping (T?,StatusList?) -> () ) {
if let url = URL(string: jsonUrlString) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Active")
guard let httpBody = try? JSONSerialization.data(withJSONObject: param, options: []) else { return }
request.httpBody = httpBody
print("REQUEST : \(request) \n PARAMETERES : \(param)")
URLSession.shared.dataTask(with: request) { (data, response, error) in
// print("RESPONSE : \(data) === \(response) == \(error)")
if error == nil {
if let receivedData = data {
do {
let data = try JSONDecoder().decode(T.self, from: receivedData)
// print("DATA GET ON REQUEST :" ,data)
completionHandler(data,nil)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
completionHandler(nil,StatusList(status: 0, title: "", message: "Something went wrong", tag: nil))
}
return
}
}
completionHandler(nil,StatusList(status: 0, title: "", message: "Something went wrong. Please try again.", tag: nil))
// guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
// else {
// print("error: not a valid http response")
// completionHandler(nil,StatusList(status: 0, title: "", message: "Something went wrong. Please try again.", tag: nil))
// return
// }
// switch (httpResponse.statusCode) {
// case 200:
// do {
// let data = try JSONDecoder().decode(T.self, from: receivedData)
// print("DATA GET ON REQUEST :" ,data)
//
// completionHandler(data,nil)
// } catch let jsonErr {
// print("Error serializing json:", jsonErr)
// }
// break
// default:
// completionHandler(nil,StatusList(status: 0, title: "", message: "Something went wrong. Please try again.", tag: nil))
// break
// }
}.resume()
}
}
}
//
//class NetworkClass: UIViewController {
//
// override func viewDidLoad() {
// super.viewDidLoad()
// let parameters = ["base": "GBP","symbols": "CAD,EUR,USD,GBP"]
// let jsonUrlString = "\(AppConfig().url)/getEquivalentRates/"
// guard let url = URL(string: jsonUrlString) else { return }
// var request = URLRequest(url: url)
// request.httpMethod = "POST"
// request.setValue("application/json", forHTTPHeaderField: "Content-Type")
//
// guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
// request.httpBody = httpBody
//
// print("REQUEST : \(request) \\ PARAMETERES : \(parameters)")
// URLSession.shared.dataTask(with: request) { (data, response, error) in
//
// guard let data = data else { return }
//
// do {
// // let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
// // print(websiteDescription.name, websiteDescription.description)
//
//// let courses = try JSONDecoder().decode(Welcome.self, from: data)
//// print(courses)
//
// //Swift 2/3/ObjC
// // guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else { return }
// //
// // let course = Course(json: json)
// // print(course.name)
//
// } catch let jsonErr {
// print("Error serializing json:", jsonErr)
// }
//
//
// }.resume()
//
// }
//
// func networkRequest(param : [String: Any],completionHandler: ([Course]) -> Void) {
//
//
//
//
// }
//
// func makeRequest() {
//
// }
//
//
// // URLSession.shared.dataTask(with: url) { (data, response, err) in
// // //perhaps check err
// // //also perhaps check response status 200 OK
// //
// // guard let data = data else { return }
// //
// // // let dataAsString = String(data: data, encoding: .utf8)
// // // print(dataAsString)
// //
// // do {
// // // let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
// // // print(websiteDescription.name, websiteDescription.description)
// //
// // let courses = try JSONDecoder().decode([Course].self, from: data)
// // print(courses)
// //
// // //Swift 2/3/ObjC
// // // guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else { return }
// // //
// // // let course = Course(json: json)
// // // print(course.name)
// //
// // } catch let jsonErr {
// // print("Error serializing json:", jsonErr)
// // }
// //
// //
// //
// // }.resume()
// //
// // // let myCourse = Course(id: 1, name: "my course", link: "some link", imageUrl: "some image url")
// // // print(myCourse)
// // }
//
//}
//
//
//
//
////class NetworkService<T: Mappable> {
////
//// var hasInternet: Bool
////
//// init() {
//// self.hasInternet = NetworkReachabilityManager()!.isReachable
//// }
////
//// func requestForNetworkDataPost(_ data : Dictionary<String, Any>) -> Observable<Response<T>> {
//// if hasInternet {
//// return Observable<Response<T>>.create { observer in
//// let request = Alamofire.request(Endpoints.APIEndpoint.api.url, method: .post, parameters : data)
//// .validate()
//// .responseObject(completionHandler: { (response: DataResponse<Response<T>>) in
//// switch response.result {
//// case .success(let object) :
//// observer.onNext(object)
//// observer.onCompleted()
//// case .failure(let error) :
//// observer.onError(error)
//// log.info("ERROR CONNECTING TO SERVER : \(error.localizedDescription)")
//// }
//// })
//// return Disposables.create(with: { request.cancel() })
//// }
//// } else {
//// return Observable.error(NSError(domain:"", code:0, userInfo:[NSLocalizedDescriptionKey: "No internet connection"]))
//// }
//// }
////}
//
//
//
//
|
import RxSwift
protocol ViewModelType: ErrorViewModelType {
var screenNameObservable: Observable<String> {get}
var didLoad: Observable<Error?> { get }
var presentLoadingView: Observable<Bool> { get }
var presentErrorView: Observable<Bool> { get }
/// Request first page data with loadingView
func reload()
func requestData()
func refreshData()
}
class ViewModel: ViewModelType {
// MARK: - LyfeCycle properties
var setDidLoad: PublishSubject<Error?> = PublishSubject()
lazy var didLoad: Observable<Error?> = self.setDidLoad.asObservable()
// MARK: - Present Views properties
lazy var screenNameObservable: Observable<String> = self.screenNameVariable.asObservable()
var screenNameVariable: Variable<String> = Variable("")
lazy var presentLoadingView: Observable<Bool> = self.presentLoadingViewVariable.asObservable()
var presentLoadingViewVariable: Variable<Bool> = Variable(false)
lazy var presentErrorView: Observable<Bool> = self.presentErrorViewVariable.asObservable()
var presentErrorViewVariable: Variable<Bool> = Variable(false)
var errorDescriptionViewVariable: Variable<String> = Variable("")
// MARK: - Private
fileprivate let router: RouterType
fileprivate let bag = DisposeBag()
init(router: RouterType) {
self.router = router
setupCommonRx()
}
deinit {
print("DEINIT: \(self)")
}
// MARK: - Request Data
func reload() {
presentLoadingViewVariable.value = true
requestData()
}
func refreshData() {
requestData()
}
func requestData() {
}
func setupCommonRx() {
didLoad
.subscribe(onNext:{ [weak self] error in
guard let strongSelf = self else { return }
strongSelf.presentLoadingViewVariable.value = false
if let error = error {
strongSelf.manageError(error)
} else {
strongSelf.presentErrorViewVariable.value = false
}
})
.disposed(by:bag)
}
// MARK: - Errors
func manageError(_ error: Error) {
switch error {
// Internet Errors
case ApiError.noInternetConection:
presentErrorViewVariable.value = true
errorDescriptionViewVariable.value = "noInternetConection".localized
case ApiError.networkException:
presentErrorViewVariable.value = true
errorDescriptionViewVariable.value = "noInternetConection".localized
case ApiError.timeOut:
presentErrorViewVariable.value = true
errorDescriptionViewVariable.value = "noInternetConection".localized
default:
break
}
}
}
extension ViewModel: ErrorViewModelType {
var descriptionText: Observable<String> {
return errorDescriptionViewVariable.asObservable()
}
var buttonText: Observable<String> {
return Observable.of("retry".localized)
}
func buttonTaped() {
self.reload()
}
}
|
///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
//
// TokenExtension.swift
// Antlr.swift
//
// Created by janyou on 15/9/4.
//
import Foundation
extension Token {
static public var INVALID_TYPE: Int {
return 0
}
///
/// During lookahead operations, this "token" signifies we hit rule end ATN state
/// and did not follow it despite needing to.
///
static public var EPSILON: Int {
return -2
}
static public var MIN_USER_TOKEN_TYPE: Int {
return 1
}
static public var EOF: Int {
return -1
}
///
/// All tokens go to the parser (unless skip() is called in that rule)
/// on a particular "channel". The parser tunes to a particular channel
/// so that whitespace etc... can go to the parser on a "hidden" channel.
///
static public var DEFAULT_CHANNEL: Int {
return 0
}
///
/// Anything on different channel than DEFAULT_CHANNEL is not parsed
/// by parser.
///
static public var HIDDEN_CHANNEL: Int {
return 1
}
///
/// This is the minimum constant value which can be assigned to a
/// user-defined token channel.
///
///
/// The non-negative numbers less than _#MIN_USER_CHANNEL_VALUE_ are
/// assigned to the predefined channels _#DEFAULT_CHANNEL_ and
/// _#HIDDEN_CHANNEL_.
///
/// - seealso: org.antlr.v4.runtime.Token#getChannel()
///
static public var MIN_USER_CHANNEL_VALUE: Int {
return 2
}
}
|
//
// UIImageView+Extension.swift
// 小峰微博
//
// Created by apple on 17/11/23.
// Copyright © 2017年 Student. All rights reserved.
//
import UIKit
extension UIImageView
{
convenience init(imageName:String)
{
self.init(image:UIImage(named:imageName))
}
}
|
//
// RootViewController.swift
// iOSPHAssetDemoApp
//
// Created by Yuki Okudera on 2020/02/05.
// Copyright © 2020 Yuki Okudera. All rights reserved.
//
import UIKit
final class RootViewController: UIViewController {
var presenter: RootViewPresentation!
private var activityIndicator: UIActivityIndicatorView?
override func viewDidLoad() {
super.viewDidLoad()
setupActivityIndicator()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.activityIndicator?.startAnimating()
// 直近の動画を1件Documents/videosに保存する
presenter.requestVideosFetching()
// 直近の画像を1枚Documents/photosに保存する
// presenter.requestPhotosFetching()
}
private func setupActivityIndicator() {
self.activityIndicator = .init(style: .gray)
self.activityIndicator!.center = self.view.center
self.activityIndicator!.hidesWhenStopped = true
self.view.addSubview(self.activityIndicator!)
}
}
extension RootViewController: RootView {
func showAlert(title: String, message: String) {
DispatchQueue.main.async { [weak self] in
guard let `self` = self else { return }
self.activityIndicator?.stopAnimating()
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
}
|
//
// UIAttributedActionSheet.swift
// Pocket Clouds
//
// Created by Tyler on 06/06/2017.
// Copyright © 2017 TylerSwann. All rights reserved.
//
import Foundation
import UIKit
import Foundation
import UIKit
open class UIAttributedActionSheet: NSObject,
UITableViewDelegate,
UITableViewDataSource
{
private var reuseIdentifier = "attributedCell"
private lazy var superViewSize: CGSize = {return CGSize.init(width: self.viewController.view.frame.size.width, height: (self.viewController.view.frame.size.height))}()
private lazy var superViewCenter: CGPoint = {return CGPoint.init(x: (self.superViewSize.width / 2), y: (self.superViewSize.height / 2))}()
private lazy var view: UIView = {return UIView()}()
private var center = CGPoint.zero
open var allowsMultiSelection = false
open var toolbarItems: [UIBarButtonItem]?
open var delegate: UIAttributedActionSheetDelegate?
open private(set) var isHidden = true
open private(set) var viewController: UIViewController
private weak var tableview: UITableView?
private weak var toolbar: UIToolbar?
private weak var doneButton: UIBarButtonItem?
private var needsSetup = true
private var animationDuration: TimeInterval = 0.3
init(presentOn: UIViewController)
{
self.viewController = presentOn
}
convenience override init ()
{
self.init(presentOn: UIViewController())
}
private func setup()
{
let tableview = UITableView(frame: CGRect.init(x: 0, y: 0, width: self.superViewSize.width, height: (self.superViewSize.height / 2)), style: .plain)
tableview.register(UIAttributedActionSheetCell.self, forCellReuseIdentifier: self.reuseIdentifier)
tableview.delegate = self
tableview.dataSource = self
tableview.allowsMultipleSelection = self.allowsMultiSelection
let toolbar = UIToolbar(frame: CGRect(origin: CGPoint.zero, size: CGSize.init(width: self.superViewSize.width, height: 44)))
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneClick))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolbar.items = [flexibleSpace, doneButton]
self.view = UIView(frame: CGRect(x: 0, y: 0, width: self.superViewSize.width, height: ((self.superViewSize.height / 2) + toolbar.frame.size.height)))
self.center = CGPoint(x: (self.view.frame.size.width / 2), y: (self.view.frame.size.height / 2))
tableview.isHidden = true
toolbar.isHidden = true
self.view.isHidden = true
self.view.isUserInteractionEnabled = true
self.view.center = self.superViewCenter
self.view.center.y += ((self.superViewSize.height / 2) - (self.view.frame.size.height / 2))
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .regular))
blurView.frame = self.view.frame
self.view = blurView
self.viewController.view.addSubview(self.view)
self.view.addSubview(tableview)
self.view.addSubview(toolbar)
tableview.center = self.center
tableview.center.y += (toolbar.frame.size.height / 2)
tableview.backgroundColor = UIColor.clear
toolbar.center = self.center
toolbar.center.y -= (self.center.y - (toolbar.frame.size.height / 2))
self.view.center.y += self.viewController.view.frame.size.height
tableview.isHidden = false
toolbar.isHidden = false
self.view.isHidden = false
self.tableview = tableview
self.doneButton = doneButton
self.toolbar = toolbar
self.needsSetup = false
self.view.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleTopMargin, .flexibleHeight]
self.tableview?.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleTopMargin, .flexibleHeight]
self.toolbar?.autoresizingMask = [.flexibleWidth]
}
open func show()
{
if(needsSetup){self.setup()}
else if (!self.isHidden){self.dismiss(); return}
self.view.isHidden = false
UIView.animate(withDuration: animationDuration, animations: {
self.view.center.y -= self.viewController.view.frame.size.height
}, completion: {_ in self.isHidden = false})
}
open func dismiss()
{
if (self.isHidden){self.show(); return}
UIView.animate(withDuration: animationDuration, animations: {
self.view.center.y += self.viewController.view.frame.size.height
}, completion: {_ in self.isHidden = true; self.view.isHidden = true})
}
@objc private func doneClick()
{
self.delegate?.attributedActionSheetDidPressDone?()
self.dismiss()
}
public func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath)
{
if let cell = tableView.cellForRow(at: indexPath) as? UIAttributedActionSheetCell
{
UIView.animate(withDuration: 0.1, animations: {cell.textLabel?.alpha = CGFloat(0.1)})
}
}
public func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath)
{
if let cell = tableView.cellForRow(at: indexPath) as? UIAttributedActionSheetCell
{
UIView.animate(withDuration: 0.2, animations: {cell.textLabel?.alpha = CGFloat(1.0)})
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.delegate?.attributedActionSheet(numberOfRowsIn: section) ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if let cell = tableView.dequeueReusableCell(withIdentifier: self.reuseIdentifier, for: indexPath) as? UIAttributedActionSheetCell
{
cell.textLabel?.attributedText = self.delegate?.attributedActionSheet(titleForRowAt: indexPath.item)
return cell
}
else {return UIAttributedActionSheetCell()}
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
self.delegate?.attributedActionSheet?(didSelectRowAt: indexPath.item)
if (self.allowsMultiSelection == false){self.dismiss()}
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
self.delegate?.attributedActionSheet?(didDeSelectRowAt: indexPath.item)
}
}
|
//
// ViewController.swift
// Dicee
//
// Created by Tomas Giraldo on 10/27/17.
// Copyright © 2017 Tomas Giraldo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var randomDiceIndex1 : Int = 0
var randomDiceIndex2 : Int = 0
let diceArray = ["dice1","dice2","dice3", "dice4","dice5","dice6"]
@IBOutlet weak var diceImageView1: UIImageView!
@IBOutlet weak var diceImageView2: UIImageView!
@IBOutlet weak var rulesLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
updateDiceImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func rollButtonPressed(_ sender: Any) {
updateDiceImage()
}
func updateDiceImage (){
randomDiceIndex1 = Int(arc4random_uniform(UInt32(diceArray.count)))
randomDiceIndex2 = Int(arc4random_uniform(UInt32(diceArray.count)))
diceImageView1.image = UIImage(named : diceArray [randomDiceIndex1])
diceImageView2.image = UIImage(named : diceArray [randomDiceIndex2])
let sum = 2+randomDiceIndex1+randomDiceIndex2
if randomDiceIndex1+1 == 1 && randomDiceIndex2+1 == 1 {
rulesLabel.text = "When someone rolls double they give the dice to someone of their choosing. This person rolls the dice and must drink for that many seconds. The dice may be given to two people instead of giving both to just one person."
}
else if randomDiceIndex1+1 == 2 && randomDiceIndex2+1 == 2 {
rulesLabel.text = "When someone rolls double they give the dice to someone of their choosing. This person rolls the dice and must drink for that many seconds. The dice may be given to two people instead of giving both to just one person."
}
else if randomDiceIndex1+1 == 3 && randomDiceIndex2+1 == 3 {
rulesLabel.text = "When someone rolls double they give the dice to someone of their choosing. This person rolls the dice and must drink for that many seconds. The dice may be given to two people instead of giving both to just one person."
}
else if randomDiceIndex1+1 == 4 && randomDiceIndex2+1 == 4 {
rulesLabel.text = "When someone rolls double they give the dice to someone of their choosing. This person rolls the dice and must drink for that many seconds. The dice may be given to two people instead of giving both to just one person."
}
else if randomDiceIndex1+1 == 5 && randomDiceIndex2+1 == 5 {
rulesLabel.text = "When someone rolls double they give the dice to someone of their choosing. This person rolls the dice and must drink for that many seconds. The dice may be given to two people instead of giving both to just one person."
}
else if randomDiceIndex1+1 == 6 && randomDiceIndex2+1 == 6 {
rulesLabel.text = "When someone rolls double they give the dice to someone of their choosing. This person rolls the dice and must drink for that many seconds. The dice may be given to two people instead of giving both to just one person."
}
else if sum == 3 {
rulesLabel.text = "Whoever is the three man must drink. If the three man rolls this then he may pass the title to a person of his choosing."
}
else if sum == 4 {
rulesLabel.text = "Pass the dice!!"
}
else if sum == 6 {
rulesLabel.text = "Pass the dice!!"
}
else if sum == 8 {
rulesLabel.text = "Pass the dice!!"
}
else if sum == 7 {
rulesLabel.text = "Person to the right of “roller” drinks."}
else if sum == 9 {
rulesLabel.text = "Person across from “roller” drinks."}
else if sum == 9 {
rulesLabel.text = "Person across from “roller” drinks."}
else if sum == 10 {
rulesLabel.text = "Social…everyone drinks."}
else if sum == 11 {
rulesLabel.text = "Person to the left of “roller” drinks."}
else if randomDiceIndex1+1 == 4 && randomDiceIndex2+1 == 1 {
rulesLabel.text = "Whoever rolls this become the Thumbmaster. They can place their thumb on the table whenever they want. The last person to do this must drink. The Thumbmaster can only change when someone else rolls a 4 & 1."}
else if randomDiceIndex1+1 == 1 && randomDiceIndex2+1 == 4 {
rulesLabel.text = "Whoever rolls this become the Thumbmaster. They can place their thumb on the table whenever they want. The last person to do this must drink. The Thumbmaster can only change when someone else rolls a 4 & 1."}
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
updateDiceImage()
}
}
|
//
// AppDelegate.swift
// PZJsonExport
//
// Created by z on 2018/4/12.
// Copyright © 2018年 z. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@IBAction func saveFiles(_ sender: Any) {
}
}
|
//
// SearchUsersNavigationController.swift
// TimeTuck_app
//
// Created by Greenstein on 2/7/15.
// Copyright (c) 2015 TimeTuck. All rights reserved.
//
import UIKit
class SearchUsersNavigationController: StandardNavigationController {
var appManager: TTAppManager?
init(_ appManager: TTAppManager) {
self.appManager = appManager;
super.init(nibName: nil, bundle: nil);
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
self.appManager = nil;
}
override func viewDidLoad() {
super.viewDidLoad();
var searchTable = SearchUserTableViewController(self.appManager!);
setViewControllers([searchTable], animated: true);
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldAutorotate() -> Bool {
return false;
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue);
}
}
|
//
// GBTextField.swift
// Post
//
// Created by Batth on 07/10/18.
// Copyright © 2018 Gurinder Batth. All rights reserved.
//
import UIKit
public protocol GBTextFieldDelegate: class{
func gbLeftView(_ textField: GBTextField?)
func gbRightView(_ textField: GBTextField?)
}
public extension GBTextFieldDelegate{
func gbLeftView(_ textField: GBTextField?){
print("Please add GBTextFieldDelegate & gbLeftView(_ textField: GBTextField?) function")
}
func gbRightView(_ textField: GBTextField?){
print("Please add GBTextFieldDelegate & gbRightView(_ textField: GBTextField?) function")
}
}
@IBDesignable
public class GBTextField: UITextField {
//MARK:- Public Properties
public weak var gbTextFieldDelegate: GBTextFieldDelegate?
@IBInspectable
public var lineHeight: CGFloat = 0{
didSet{
setupLine()
}
}
@IBInspectable
public var selectedLineHeight: CGFloat = 0{
didSet{
if selectedLineHeight == 0{
selectedLineHeight = lineHeight
}
}
}
@IBInspectable
public var labelText: String = ""{
didSet{
if labelText != ""{
self.labelPlaceholder.text = labelText
}
}
}
@IBInspectable
public var titleLabelColor: UIColor = .darkGray
public var titleFont: UIFont?{
didSet{
self.labelPlaceholder.font = titleFont
}
}
@IBInspectable
public var lineColor: UIColor = .darkGray{
didSet{
if !showError {
self.viewLine?.backgroundColor = lineColor
}else{
self.viewLine?.backgroundColor = errorColor
}
}
}
@IBInspectable
public var selectedTitleColor: UIColor = .blue
@IBInspectable
public var selectedLineColor: UIColor = .blue
@IBInspectable
public var errorColor: UIColor = .red{
didSet{
self.labelError.textColor = errorColor
if showError {
self.showErrorMessage(self.showError, self.errorMessage ?? "")
}
}
}
public var errorFont: UIFont?{
didSet{
self.labelError.font = errorFont
}
}
@IBInspectable
public var placeholderColor: UIColor?{
didSet{
#if swift(>=4.2)
self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor:placeholderColor ?? UIColor.lightGray])
#elseif swift(>=4.0)
self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor:placeholderColor ?? UIColor.lightGray])
#else
self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [NSForegroundColorAttributeName:placeholderColor ?? UIColor.lightGray])
#endif
}
}
@IBInspectable
public var rightImage: UIImage?{
didSet{
let ratio = (rightImage?.size.height)! / (rightImage?.size.width)!
let newWidth = self.frame.height / ratio
viewRight = UIView(frame: CGRect(x: 0, y: 0, width: newWidth, height: self.frame.size.height))
if viewRight != nil{
viewRight!.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rightViewSelected(_:))))
}
let imageView = UIImageView(image: rightImage)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.isUserInteractionEnabled = true
viewRight?.addSubview(imageView)
imageView.topAnchor.constraint(equalTo: viewRight!.topAnchor, constant: 7).isActive = true
imageView.leftAnchor.constraint(equalTo: viewRight!.leftAnchor, constant: 7).isActive = true
imageView.bottomAnchor.constraint(equalTo: viewRight!.bottomAnchor, constant: -7).isActive = true
imageView.rightAnchor.constraint(equalTo: viewRight!.rightAnchor, constant: -7).isActive = true
imageView.clipsToBounds = true
imageView.contentMode = .scaleToFill
self.rightView = viewRight
self.rightViewMode = .always
}
}
@IBInspectable
public var rightImageSquare: UIImage?{
didSet{
var newWidth: CGFloat = 20
if self.frame.height > 25 && self.frame.height < 30{
newWidth = 25
}else if self.frame.height >= 30{
newWidth = 30
}
let x = viewRight?.frame.origin.x ?? 0
let y = viewRight?.frame.origin.y ?? 0
viewRight = UIView(frame: CGRect(x: x, y: y, width: newWidth, height: newWidth))
if viewRight != nil{
viewRight!.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rightViewSelected(_:))))
}
let imageView = UIImageView(image: rightImageSquare)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.isUserInteractionEnabled = true
viewRight?.addSubview(imageView)
imageView.rightAnchor.constraint(equalTo: viewRight!.rightAnchor, constant: -5).isActive = true
imageView.leftAnchor.constraint(equalTo: viewRight!.leftAnchor, constant: 5).isActive = true
imageView.centerYAnchor.constraint(equalTo: self.viewRight!.centerYAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: CGFloat(newWidth - 5)).isActive = true
imageView.widthAnchor.constraint(equalToConstant: CGFloat(newWidth - 5)).isActive = true
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFit
self.rightView = viewRight
self.rightViewMode = .always
}
}
@IBInspectable
public var padding: CGFloat = 0{
didSet{
if rightImage == nil{
self.rightView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: self.frame.height))
self.rightViewMode = .always
}
if leftImage == nil{
self.leftView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: self.frame.height))
self.leftViewMode = .always
}
}
}
@IBInspectable
public var leftImage: UIImage?{
didSet{
let ratio = (leftImage?.size.height)! / (leftImage?.size.width)!
let newWidth = self.frame.height / ratio
viewLeft = UIView(frame: CGRect(x: 0, y: 0, width: newWidth, height: self.frame.size.height))
if viewLeft != nil{
viewLeft?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(leftViewSelected(_:))))
}
let imageView = UIImageView(image: leftImage)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.isUserInteractionEnabled = true
viewLeft?.addSubview(imageView)
imageView.topAnchor.constraint(equalTo: viewLeft!.topAnchor, constant: 7).isActive = true
imageView.leftAnchor.constraint(equalTo: viewLeft!.leftAnchor, constant: 7).isActive = true
imageView.bottomAnchor.constraint(equalTo: viewLeft!.bottomAnchor, constant: -7).isActive = true
imageView.rightAnchor.constraint(equalTo: viewLeft!.rightAnchor, constant: -7).isActive = true
imageView.clipsToBounds = true
imageView.contentMode = .scaleToFill
self.leftView = viewLeft
self.leftViewMode = .always
}
}
@IBInspectable
public var leftImageSquare: UIImage?{
didSet{
var newWidth = 20
if self.frame.height > 25 && self.frame.height < 30{
newWidth = 25
}else if self.frame.height >= 30{
newWidth = 30
}
viewLeft = UIView(frame: CGRect(x: 0, y: 0, width: newWidth + 14, height: newWidth))
if viewLeft != nil{
viewLeft?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(leftViewSelected(_:))))
}
let imageView = UIImageView(image: leftImageSquare)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.isUserInteractionEnabled = true
viewLeft?.addSubview(imageView)
imageView.leftAnchor.constraint(equalTo: viewLeft!.leftAnchor, constant: 5).isActive = true
imageView.rightAnchor.constraint(equalTo: viewLeft!.rightAnchor, constant:-5).isActive = true
imageView.centerYAnchor.constraint(equalTo: self.viewLeft!.centerYAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: CGFloat(newWidth - 5)).isActive = true
imageView.widthAnchor.constraint(equalToConstant: CGFloat(newWidth - 5)).isActive = true
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFit
self.leftView = viewLeft
self.leftViewMode = .always
}
}
public var rightImageClicable: Bool = false{
didSet{
if rightImageClicable{
viewRight?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rightViewSelected(_:))))
}
}
}
public var leftImageClicable: Bool = false{
didSet{
if leftImageClicable{
viewLeft?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(leftViewSelected(_:))))
}
}
}
//MARK:- Private Properties
private var viewRight: UIView?
private var viewLeft: UIView?
private var textString: String?
private var errorMessage: String?
private var defaultTextColor: UIColor?
private lazy var viewLine:UIView? = {
let prntView = UIView()
prntView.translatesAutoresizingMaskIntoConstraints = false
return prntView
}()
private lazy var labelPlaceholder: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.textColor = .clear
lbl.font = self.font
return lbl
}()
private lazy var labelError: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.font = self.font
lbl.textAlignment = .right
lbl.numberOfLines = 0
lbl.font = UIFont.boldSystemFont(ofSize: 12)
return lbl
}()
private var constraintFloatingLabelTop: NSLayoutConstraint!
private var constraintFloatingLabelLeft: NSLayoutConstraint!
private var constraintFloatingLabelHeight: NSLayoutConstraint!
private var constraintLineHeight: NSLayoutConstraint?
private var showError: Bool = false{
didSet{
if showError{
self.setupError()
}else{
if isEditing{
self.viewLine?.backgroundColor = selectedLineColor
self.labelPlaceholder.textColor = selectedTitleColor
}else{
self.viewLine?.backgroundColor = lineColor
self.labelPlaceholder.textColor = titleLabelColor
}
self.textColor = self.defaultTextColor
self.labelError.isHidden = true
}
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.addViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addViews()
}
public override func prepareForInterfaceBuilder() {
self.addViews()
}
public override var text: String?{
set{
self.textString = newValue
super.text = newValue
if !(newValue?.isEmpty ?? true){
self.showFloatingLabel()
}
}get{
return super.text
}
}
public override var textColor: UIColor?{
set{
if newValue != errorColor {
self.defaultTextColor = newValue
}
if !self.showError{
super.textColor = newValue
}else{
super.textColor = self.errorColor
}
}get{
return super.textColor
}
}
public func showErrorMessage(_ showError: Bool = true, _ error: String = ""){
if showError {
self.errorMessage = error
self.setupError()
self.labelError.isHidden = false
labelError.textColor = errorColor
labelError.text = error
viewLine?.backgroundColor = errorColor
self.textColor = errorColor
self.labelPlaceholder.textColor = errorColor
}
self.showError = showError
if (self.text?.isEmpty ?? true){
self.hideFloatingLabel()
}
}
//MARK:- Private Functions
@objc private func rightViewSelected(_ gesture: UITapGestureRecognizer){
let textField = gesture.view?.superview as? GBTextField
self.gbTextFieldDelegate?.gbRightView(textField)
}
@objc private func leftViewSelected(_ gesture: UITapGestureRecognizer){
let textField = gesture.view?.superview as? GBTextField
self.gbTextFieldDelegate?.gbLeftView(textField)
}
private func addViews(){
self.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
for subView in self.subviews{
if subView == labelPlaceholder{
return
}
}
addSubview(labelPlaceholder)
if labelText != ""{
labelPlaceholder.text = labelText
}else{
labelPlaceholder.text = placeholder
}
self.constraintFloatingLabelTop = self.labelPlaceholder.topAnchor.constraint(equalTo: topAnchor, constant: 0)
self.constraintFloatingLabelTop.isActive = true
self.labelPlaceholder.leftAnchor.constraint(equalTo: self.leftView?.rightAnchor ?? self.leftAnchor).isActive = true
self.labelPlaceholder.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
self.constraintFloatingLabelHeight = self.labelPlaceholder.heightAnchor.constraint(equalTo: self.heightAnchor, constant: 0)
self.constraintFloatingLabelHeight.isActive = true
self.labelPlaceholder.textAlignment = self.textAlignment
if (self.text?.count ?? 0) > 0{
self.setupLine()
self.textFieldDidChange(self)
self.resignFirstResponder()
}
self.defaultTextColor = self.textColor
}
private func setupLine(){
if lineHeight != 0{
for subview in self.subviews{
if subview == self.viewLine{
return
}
}
if viewLine != nil{
addSubview(self.viewLine!)
viewLine?.topAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
viewLine?.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
viewLine?.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
constraintLineHeight = viewLine?.heightAnchor.constraint(equalToConstant: lineHeight)
viewLine?.backgroundColor = lineColor
constraintLineHeight?.isActive = true
}
}
}
private func setupError(){
for subview in self.subviews{
if subview == self.labelError{
return
}
}
addSubview(self.labelError)
labelError.topAnchor.constraint(equalTo: self.bottomAnchor, constant: lineHeight + 3).isActive = true
labelError.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
labelError.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
labelError.textColor = errorColor
}
public override var isSecureTextEntry: Bool{
set{
super.isSecureTextEntry = newValue
fixSecureEntry()
}get{
return super.isSecureTextEntry
}
}
@discardableResult
override public func becomeFirstResponder() -> Bool {
self.setupLabelText()
if !showError{
self.viewLine?.backgroundColor = selectedLineColor
}
let count = self.text?.count ?? 0
if count == 0{
return super.becomeFirstResponder()
}
if selectedLineHeight == 0{
constraintLineHeight?.constant = lineHeight
}else{
constraintLineHeight?.constant = selectedLineHeight
}
if count > 0{
self.labelPlaceholder.textColor = selectedTitleColor
if showError{
viewLine?.backgroundColor = errorColor
labelPlaceholder.textColor = errorColor
}
self.showFloatingLabel()
if self.showError{
self.labelPlaceholder.textColor = self.errorColor
}else{
self.labelPlaceholder.textColor = self.selectedTitleColor
}
}
return super.becomeFirstResponder()
}
@discardableResult
override public func resignFirstResponder() -> Bool {
constraintLineHeight?.constant = lineHeight
self.viewLine?.backgroundColor = lineColor
if let count = self.text?.count{
if count > 0{
self.labelPlaceholder.textColor = titleLabelColor
}else{
self.labelPlaceholder.textColor = .clear
}
if showError{
viewLine?.backgroundColor = errorColor
labelPlaceholder.textColor = errorColor
}
}else{
self.labelPlaceholder.textColor = .clear
}
return super.resignFirstResponder()
}
@objc private func textFieldDidChange(_ textField:UITextField){
if let text = self.text{
if text.count > 0{
labelPlaceholder.isHidden = false
if self.constraintFloatingLabelTop.constant != -15{
self.showFloatingLabel()
}
}else{
self.hideFloatingLabel()
}
}
}
private func setupLabelText(){
if labelText != ""{
labelPlaceholder.text = labelText
}else{
labelPlaceholder.text = placeholder
}
if (self.text?.isEmpty ?? true){
self.hideFloatingLabel()
}
}
private func showFloatingLabel(){
self.setupLabelText()
self.constraintFloatingLabelHeight.isActive = false
self.constraintFloatingLabelTop.constant = -15
self.labelPlaceholder.font = UIFont.boldSystemFont(ofSize: 12)
if self.showError{
self.labelPlaceholder.textColor = self.errorColor
}else{
if self.isEditing{
self.labelPlaceholder.textColor = self.selectedTitleColor
}else{
self.labelPlaceholder.textColor = self.titleLabelColor
}
}
UIView.transition(with: self.labelPlaceholder, duration: 0.2, options: .transitionCrossDissolve, animations: {
self.layoutIfNeeded()
}) { (completed) in
}
}
private func hideFloatingLabel(){
self.constraintFloatingLabelHeight.isActive = false
self.constraintFloatingLabelHeight = self.labelPlaceholder.heightAnchor.constraint(equalTo: self.heightAnchor, constant: 0)
self.constraintFloatingLabelHeight.isActive = true
self.constraintFloatingLabelTop.constant = 20
UIView.transition(with: self.labelPlaceholder, duration: 0.2, options: .transitionCrossDissolve, animations: {
self.layoutIfNeeded()
self.labelPlaceholder.font = self.font
self.labelPlaceholder.textColor = .clear
}) { (completed) in
}
}
}
|
//
// CoreTest.swift
// RecipeApp
//
// Created by Amir Rezvani on 4/29/15.
// Copyright (c) 2015 cjcoaxapps. All rights reserved.
//
import XCTest
class CoreTests: XCTestCase {
var jsonString = "{ \"recipes\": [ { \"name\": \"Super Beef Burrito\", \"details\": \"Food coma guaranteed\", \"category\": \"Beef\", \"ingredients\": [ {\"item\": \"Tortilla\"}, {\"item\": \"Beef\"}, {\"item\": \"Beans\"}, {\"item\": \"Rice\"}, {\"item\": \"Salsa\"}, {\"item\": \"Guacamole\"}, {\"item\": \"Cheese\"}, {\"item\": \"Sour cream\"} ], \"instructions\": [ {\"step\": \"Cook beef, beans, and rice.\"}, {\"step\": \"Spread onto tortilla.\"}, {\"step\": \"Add salsa, guacamole, cheese, and sour cream.\"}, {\"step\": \"Roll up tortilla.\"} ], \"thumbnail\": \"burrito_thumbnail\", \"banner\": \"burrito_banner\" } ] } "
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testGetRecipeJson() {
let jsonParser = JsonParser()
let json = jsonParser.getRecipeJson()
XCTAssertTrue(json != nil, "json object was expected, but is nil!")
}
func testRecipeMapper() {
let jsonData = (jsonString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let json = JSON(data:jsonData!,options: .MutableContainers)
let recipeMapper = RecipeMapper()
let recipes = recipeMapper.map(json)
if let recipes = recipes {
XCTAssertEqual(recipes.count, 1, "invalid number of recipes!")
if let ingredients = recipes[0].ingredients {
XCTAssertEqual(ingredients.count, 8, "invalid number of ingredients")
} else {
XCTFail("ingredients was nil!")
}
} else {
XCTFail("Recipes was nil!")
}
}
func testConvertRecipesBaseOnCategories() {
var recipes = [Recipe]()
recipes.append(Recipe(name: "beef1",
details: nil,
category: "beef",
ingredients: nil,
instructions: nil,
thumbnail: nil,
banner: nil))
recipes.append(Recipe(name: "beef2",
details: nil,
category: "beef",
ingredients: nil,
instructions: nil,
thumbnail: nil,
banner: nil))
recipes.append(Recipe(name: "chicken1",
details: nil,
category: "chicken",
ingredients: nil,
instructions: nil,
thumbnail: nil,
banner: nil))
let recipeGetter = RecipeGetter()
let result = recipeGetter.convertRecipesBaseOnCategories(recipes)
if let result = result {
XCTAssertEqual(result[.Beef]!.count, 2, "incorrect number of items")
} else {
XCTFail("converted recipes was nil!")
}
}
}
|
//
// PlaceSelectController.swift
// GardenCoceral
//
// Created by TongNa on 2018/4/16.
// Copyright © 2018年 tongna. All rights reserved.
//
import UIKit
class PlaceSelectController: BaseViewController {
var search: AMapSearchAPI!
var tableView = UITableView()
var centerAnnotationView = UIImageView()
var mapView = MAMapView()
var searchPoiArray: Array<AMapPOI> = Array()
var isLocated: Bool = false
var isMapViewRegionChangedFromTableView: Bool = false
var selectedIndexPath: IndexPath?
var backPlace: ((AMapPOI)->())?
var searchController: UISearchController?
let searchView = UIView()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
mapView.zoomLevel = 17
mapView.isShowsUserLocation = true
}
override func viewDidLoad() {
super.viewDidLoad()
title = "地点选择"
create()
}
}
extension PlaceSelectController: AMapSearchDelegate, MAMapViewDelegate {
func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
searchPoiArray.removeAll()
searchPoiArray.append(contentsOf: response.pois)
tableView.reloadData()
}
func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
if !updatingLocation {
return
}
if userLocation.location.horizontalAccuracy < 0 {
return
}
if !self.isLocated {
self.isLocated = true
self.mapView.userTrackingMode = .follow
self.mapView.centerCoordinate = userLocation.location.coordinate
self.actionSearchAround(at: userLocation.location.coordinate)
}
}
}
extension PlaceSelectController {
func actionSearchAround(at coordinate: CLLocationCoordinate2D) {
self.searchReGeocode(withCoordinate: coordinate)
self.searchPoi(withCoordinate: coordinate)
}
func searchPoi(withCoordinate coord: CLLocationCoordinate2D) {
let request = AMapPOIAroundSearchRequest()
request.location = AMapGeoPoint.location(withLatitude: CGFloat(coord.latitude), longitude: CGFloat(coord.longitude))
request.radius = 1000
request.sortrule = 0
self.search.aMapPOIAroundSearch(request)
}
func searchReGeocode(withCoordinate coord: CLLocationCoordinate2D) {
let request = AMapReGeocodeSearchRequest()
request.location = AMapGeoPoint.location(withLatitude: CGFloat(coord.latitude), longitude: CGFloat(coord.longitude))
request.requireExtension = true
self.search.aMapReGoecodeSearch(request)
}
func mapView(_ mapView: MAMapView!, regionDidChangeAnimated animated: Bool) {
if !self.isMapViewRegionChangedFromTableView && self.mapView.userTrackingMode == .none {
self.actionSearchAround(at: self.mapView.centerCoordinate)
}
self.isMapViewRegionChangedFromTableView = false
}
}
extension PlaceSelectController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchPoiArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "place") as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "place")
}
let poi = searchPoiArray[indexPath.row]
cell?.textLabel?.text = poi.name
cell?.detailTextLabel?.text = poi.address
return cell!
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell: UITableViewCell? = tableView.cellForRow(at: indexPath)
if cell != nil {
cell!.accessoryType = UITableViewCellAccessoryType.none
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell: UITableViewCell? = tableView.cellForRow(at: indexPath)
cell?.accessoryType = UITableViewCellAccessoryType.checkmark
self.selectedIndexPath = indexPath
}
}
extension PlaceSelectController: UISearchControllerDelegate {
func didDismissSearchController(_ searchController: UISearchController) {
searchView.fadeIn()
}
}
extension PlaceSelectController {
func create() {
search = AMapSearchAPI()
search.delegate = self
_ = mapView.then{
view.addSubview($0)
$0.snp.makeConstraints({ (m) in
m.left.right.equalToSuperview()
m.top.equalTo(0)
m.height.equalTo(windowHeight/3+navigationBarHeight)
})
$0.delegate = self
}
_ = centerAnnotationView.then{
mapView.addSubview($0)
$0.snp.makeConstraints({ (m) in
m.centerX.equalTo(mapView.snp.centerX)
m.bottom.equalTo(mapView.snp.centerY)
m.width.equalTo(18)
m.height.equalTo(30)
})
$0.image = UIImage(named: "wateRedBlank")
}
tableView = UITableView(frame: .zero, style: .plain).then{
$0.backgroundColor = .white
view.addSubview($0)
$0.snp.makeConstraints({ (m) in
m.left.right.bottom.equalTo(0)
m.top.equalTo(mapView.snp.bottom)
})
$0.rowHeight = 60
$0.delegate = self
$0.dataSource = self
$0.tableFooterView = UIView()
}
let rightBtn = UIBarButtonItem(title: "确定", style: .plain, target: self, action: #selector(confirm))
navigationItem.rightBarButtonItem = rightBtn
_ = searchView.then{
mapView.addSubview($0)
$0.snp.makeConstraints({ (m) in
m.top.left.equalTo(20)
m.right.equalTo(-20)
m.height.equalTo(44)
})
$0.backgroundColor = .white
$0.addShadow()
let tap = UITapGestureRecognizer()
tap.addTarget(self, action: #selector(showSearchController))
$0.addGestureRecognizer(tap)
}
let searchLogo = UIImageView().then{
searchView.addSubview($0)
$0.snp.makeConstraints({ (m) in
m.centerY.equalToSuperview()
m.left.equalTo(20)
m.width.height.equalTo(22)
})
$0.image = #imageLiteral(resourceName: "搜索")
}
_ = UILabel().then{
searchView.addSubview($0)
$0.snp.makeConstraints({ (m) in
m.left.equalTo(searchLogo.snp.right).offset(10)
m.top.bottom.equalToSuperview()
m.right.equalToSuperview()
})
$0.text = "查找地点"
$0.textColor = UIColor(hex: "#999")
$0.font = UIFont.systemFont(ofSize: 16)
}
let searchVC = PlaceSearchResultController()
searchVC.backPlace = { poi in
self.searchView.fadeIn()
let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(poi.location.latitude), longitude: CLLocationDegrees(poi.location.longitude))
self.mapView.userTrackingMode = .follow
self.mapView.centerCoordinate = coordinate
self.actionSearchAround(at: coordinate)
}
let searchController = UISearchController(searchResultsController: searchVC)
searchController.delegate = self
searchController.searchResultsUpdater = searchVC
self.searchController = searchController
}
@objc func showSearchController() {
self.present(searchController!, animated: true, completion: nil)
searchView.fadeOut()
}
@objc func confirm() {
navigationController?.popViewController()
if let back = self.backPlace {
back(searchPoiArray[selectedIndexPath?.row ?? 0])
}
}
}
|
public enum RequestBuilderError {
case cantInitializeUrl
case cantSerializeHttpBody
}
public enum ApiClientError {
case decodingFailure
case attemptToSendAuthorizedRequest
case cantBuildUrl(RequestBuilderError)
}
public enum UploadMultipartError {
case invalidData
case cantDecodeSuccessResponse
case cantDecodeFailureResponse
}
public enum RequestError<ApiErrorType> {
case networkError(Error) // Got error from low level services
case apiClientError(ApiClientError) // Emited error
case httpUnauthenticated
case apiError(ApiErrorType) // Got error from API
case forbidden
case cantUploadMultipart(UploadMultipartError)
var isUnauthenticated: Bool {
if case .httpUnauthenticated = self {
return true
} else {
return false
}
}
}
typealias ApiResult<T> = DataResult<T, RequestError<Error>>
|
//
// ContentView.swift
// MeetupRemainder
//
// Created by Vegesna, Vijay V EX1 on 9/12/20.
// Copyright © 2020 Vegesna, Vijay V. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var membersList = [Member]()
@State var image: Image?
@State var inputImage: UIImage?
@State var activeSheet: ActiveSheet?
enum ActiveSheet: String, Identifiable {
var id: String {
rawValue
}
case image, name
}
var body: some View {
let imageBinding = Binding(
get: {
self.inputImage
}, set: {
self.inputImage = $0
self.enterPhotoName()
})
return NavigationView {
VStack {
List(membersList, id: \.name) { member in
NavigationLink(
destination: ImageDetailView(selectedMember: member)) {
HStack {
member.image
.resizable()
.scaledToFit()
.frame(width: 50, height: 50)
Text(member.name)
}
}
}
.onAppear(perform: loadData)
Spacer()
HStack{
Spacer()
Button(action: {
self.activeSheet = .image
}) {
Image(systemName: "person.badge.plus")
.font(.title)
.padding(.trailing)
}
}
.padding()
}
.navigationBarTitle("Members")
.sheet(item: $activeSheet) { currentSheet in
if currentSheet == .image {
ImagePicker(inputImage: imageBinding)
} else if currentSheet == .name {
PhotoNameView { name, location in
var codableInstance: CodableMKPointAnnotation?
if let location = location {
codableInstance = CodableMKPointAnnotation()
codableInstance?.coordinate = location
}
self.buildMember(name: name, instance: codableInstance)
}
}
}
}
}
func enterPhotoName() {
if let uiImage = inputImage {
image = Image(uiImage: uiImage)
activeSheet = .name
}
}
func buildMember(name: String, instance: CodableMKPointAnnotation?) {
guard let selectedImage = self.inputImage else { return }
let member = Member(name: name, image: selectedImage, instance: instance)
membersList.append(member)
activeSheet = .none
saveData()
}
func getDocumentsDirectory() -> URL {
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return path[0]
}
func loadData() {
let fileName = getDocumentsDirectory().appendingPathComponent("SavedMembers")
do {
let data = try Data(contentsOf: fileName)
membersList = try JSONDecoder().decode([Member].self, from: data)
} catch {
print("Unable to load saved data")
}
}
func saveData() {
let fileName = getDocumentsDirectory().appendingPathComponent("SavedMembers")
do {
let data = try JSONEncoder().encode(self.membersList)
try data.write(to: fileName, options: [.atomicWrite, .completeFileProtection])
} catch {
print("Unable to save data")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// PTPlaceSearchViewController.swift
// wwg
//
// Created by dewey on 2018. 7. 16..
// Copyright © 2018년 dewey. All rights reserved.
//
import UIKit
import RealmSwift
class PTPlaceSearchViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var placeType: PTPlaceType = .unknown
var searchResult: List<PTPlace>?
var currentSearchText: String?
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.tableView.delegate = self
self.tableView.dataSource = self
self.searchBar.becomeFirstResponder()
}
func close() {
self.dismiss(animated: true, completion: nil)
}
}
extension PTPlaceSearchViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResult?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cells")
if cell == nil {
cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "cells")
}
if let place = searchResult?[indexPath.row] {
cell?.textLabel?.text = place.name
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.searchBar.resignFirstResponder()
if let place = searchResult?[indexPath.row] {
let popupView = PTPlacePopupView(frame: CGRect(x: 0, y: 0, width: PTPlacePopupView.defaultSize().width, height: PTPlacePopupView.defaultSize().height))
popupView.placeType = self.placeType
popupView.place = place
PTPopupViewManager.showPopupView(popupView, withAnimation: true)
PTPopupViewManager.delegate = self
// get google info
PTApiRequest.request().getGoogleInfo(place: place).observeCompletion { (response) in
if response.isSuccess == true {
print(response)
}
}
}
}
}
extension PTPlaceSearchViewController: UISearchBarDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
self.close()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if let currentText = self.currentSearchText {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(search), object: currentText)
}
self.currentSearchText = searchText
self.perform(#selector(search), with: self.currentSearchText, afterDelay: 0.5)
}
@objc func search(_ searchText: String) {
self.currentSearchText = nil
debugPrint("search: \(searchText)")
if searchText.count != 0 {
PTPlaceSearchHelper.shared.search(searchText) { (isSuccess, result) in
self.showSearchResult(success: isSuccess, result: result)
}
}
}
func showSearchResult(success: Bool, result: [[String: Any]]?) {
if let json = result, json.count > 0 && success == true {
debugPrint("success search")
self.searchResult = PTPlace.createPlaces(placeInfos: json)
self.tableView.reloadData()
} else {
debugPrint("failed search")
// show empty or failed search display
}
}
}
extension PTPlaceSearchViewController: PTPopupViewShareDelegate {
func popupViewStateShare(state: PTPopupViewState) {
if case .closed = state {
self.searchBar.becomeFirstResponder()
}
}
}
|
import Async
import Bits
import NIO
final class PostgreSQLMessageDecoder: ByteToMessageDecoder {
/// See `ByteToMessageDecoder.InboundOut`
public typealias InboundOut = PostgreSQLMessage
/// The cumulationBuffer which will be used to buffer any data.
var cumulationBuffer: ByteBuffer?
/// Decode from a `ByteBuffer`. This method will be called till either the input
/// `ByteBuffer` has nothing to read left or `DecodingState.needMoreData` is returned.
///
/// - parameters:
/// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
/// - buffer: The `ByteBuffer` from which we decode.
/// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called
// again once more data is present in the `ByteBuffer`.
func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
VERBOSE("PostgreSQLMessageDecoder.decode(ctx: \(ctx), buffer: \(buffer)")
/// peek at messageType
guard let messageType: Byte = buffer.peekInteger() else {
VERBOSE(" [needMoreData: messageType=nil]")
return .needMoreData
}
//// peek at messageSize
guard let messageSize: Int32 = buffer.peekInteger(skipping: MemoryLayout<Byte>.size) else {
// message can still be a SSL Request
if messageType == .S || messageType == .N {
if let data = buffer.readSlice(length: 1) {
let decoder = _PostgreSQLMessageDecoder(data: data)
let message = try PostgreSQLMessage.sslRequest(decoder.decode())
ctx.fireChannelRead(wrapInboundOut(message))
return .continue
}
}
VERBOSE(" [needMoreData: messageSize=nil]")
return .needMoreData
}
/// ensure message is large enough or reject
guard buffer.readableBytes - MemoryLayout<Byte>.size >= Int(messageSize) else {
VERBOSE(" [needMoreData: readableBytes=\(buffer.readableBytes), messageSize=\(messageSize)]")
return .needMoreData
}
/// skip messageType and messageSize
buffer.moveReaderIndex(forwardBy: MemoryLayout<Byte>.size + MemoryLayout<Int32>.size)
/// read messageData
guard let messageData = buffer.readSlice(length: Int(messageSize) - MemoryLayout<Int32>.size) else {
fatalError("buffer.readSlice returned nil even though length was checked.")
}
let decoder = _PostgreSQLMessageDecoder(data: messageData)
let message: PostgreSQLMessage
switch messageType {
case .E: message = try .error(decoder.decode())
case .N: message = try .notice(decoder.decode())
case .R: message = try .authenticationRequest(decoder.decode())
case .S: message = try .parameterStatus(decoder.decode())
case .K: message = try .backendKeyData(decoder.decode())
case .Z: message = try .readyForQuery(decoder.decode())
case .T: message = try .rowDescription(decoder.decode())
case .D: message = try .dataRow(decoder.decode())
case .C: message = try .close(decoder.decode())
case .one: message = .parseComplete
case .two: message = .bindComplete
case .n: message = .noData
case .t: message = try .parameterDescription(decoder.decode())
default:
let string = String(bytes: [messageType], encoding: .ascii) ?? "n/a"
throw PostgreSQLError(
identifier: "decoder",
reason: "Unrecognized message type: \(string) (\(messageType))",
possibleCauses: ["Connected to non-PostgreSQL database"],
suggestedFixes: ["Connect to PostgreSQL database"],
source: .capture()
)
}
VERBOSE(" [message=\(message)]")
ctx.fireChannelRead(wrapInboundOut(message))
return .continue
}
/// Temporary
func channelInactive(ctx: ChannelHandlerContext) {
ctx.fireChannelInactive()
}
/// Called once this `ByteToMessageDecoder` is removed from the `ChannelPipeline`.
///
/// - parameters:
/// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
func decoderRemoved(ctx: ChannelHandlerContext) {
VERBOSE("PostgreSQLMessageDecoder.decoderRemoved(ctx: \(ctx))")
}
/// Called when this `ByteToMessageDecoder` is added to the `ChannelPipeline`.
///
/// - parameters:
/// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
func decoderAdded(ctx: ChannelHandlerContext) {
VERBOSE("PostgreSQLMessageDecoder.decoderAdded(ctx: \(ctx))")
}
}
|
/*
Erbele - Based on Fraise 3.7.3 based on Smultron by Peter Borg
Current Maintainer (since 2016):
Andreas Bentele: abentele.github@icloud.com (https://github.com/abentele/Erbele)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import Foundation
class FRAEditMenuController : NSObject, NSMenuItemValidation {
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool
{
var enableMenuItem = true
let tag = menuItem.tag
if (tag == 1 || tag == 11 || tag == 111) { // All items that should only be active when there's text to select/delete
if (FRACurrentTextView() == nil) {
enableMenuItem = false;
}
} else if (tag == 2) { // Live Find
if (FRACurrentProject()?.areThereAnyDocuments() == false) {
enableMenuItem = false;
}
}
return enableMenuItem;
}
@IBAction func advancedFindReplaceAction(_ sender: Any) {
FRAAdvancedFindController.sharedInstance().showAdvancedFindWindow()
}
@IBAction func liveFindAction(_ sender: Any) {
let firstResponder = FRACurrentWindow()?.firstResponder
FRACurrentWindow()?.makeFirstResponder(FRACurrentProject()?.liveFindSearchField());
let fieldEditor = FRACurrentProject()?.liveFindSearchField()?.window?.firstResponder;
if (firstResponder == fieldEditor) {
FRACurrentWindow()?.makeFirstResponder(FRACurrentProject()?.lastTextViewInFocus) // If the search field is already in focus switch it back to the text, this allows the user to use the same key command to get to the search field and get back to the selected text after the search is complete
} else {
FRACurrentProject()?.prepareForLiveFind();
}
}
}
|
//
// Copyright © 2017 Essential Developer. All rights reserved.
//
import UIKit
final class SinglePlayerViewController: UIViewController {
var player: PlayerScoreViewController?
}
|
//
// CRMFilterViewController.swift
// SweepBright
//
// Created by Kaio Henrique on 4/14/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import UIKit
class CRMFilterViewController: UIViewController {
@IBOutlet weak var interestLevelFilter: SWBSwitch!
@IBOutlet weak var interestLevelFilterSliderView: UIView!
@IBOutlet weak var interestLevelFilterSlider: SWBColouredUISlider!
override func viewDidLoad() {
super.viewDidLoad()
//Hide slider if the toggle is not checked
self.interestLevelFilter.rac_valueChanged().subscribeNext({
_ in
UIView.animateWithDuration(0.4, animations: {
self.interestLevelFilterSlider.sliderLabels?.hidden = !self.interestLevelFilter.checked
self.interestLevelFilterSlider.hidden = !self.interestLevelFilter.checked
self.interestLevelFilterSliderView.hidden = !self.interestLevelFilter.checked
})
})
}
}
|
import Foundation
/*
Q424 Longest Repeating Character Replacement
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 104.
Example 1:
Input:
s = "ABAB", k = 2
Output:
4
Explanation:
Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input:
s = "AABABBA", k = 1
Output:
4
Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
*/
func characterReplacement(_ s: String, _ k: Int) -> Int {
if s.count == 0 { return 0 }
var hashMap = [Int](repeating: 0, count: 26)
var chars = [Character](s)
var length = 0
var res = 0
var left = 0
var right = 0
var change = 0
var maxCount = 0
while right < chars.count {
let currChar = chars[right]
right += 1
let currIndex = getNumIndex(char: currChar)
hashMap[currIndex] = hashMap[currIndex] + 1
maxCount = max(maxCount, hashMap[currIndex])
length += 1
change = length - maxCount
while change > k {
let prevChar = chars[left]
let prevIndex = getNumIndex(char: prevChar)
hashMap[prevIndex] = hashMap[prevIndex] - 1
for i in 0...25 {
if hashMap[i] > maxCount {
maxCount = hashMap[i]
break
}
}
length -= 1
change = length - maxCount
left += 1
}
res = max(res, length)
}
return res
}
func getNumIndex(char: Character) -> Int {
return Int(getUnicodeValue(char: char) - getUnicodeValue(char: "A"))
}
func getUnicodeValue(char: Character) -> UInt32 {
let scalars = char.unicodeScalars
return scalars[scalars.startIndex].value
}
print(characterReplacement("AABABBA", 1))
print(getUnicodeValue(char: "A")) // 65
|
//
// BillPaymentHistoryViewController.swift
// TrocoSimples
//
// Created by gustavo r meyer on 8/16/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import UIKit
class BillPaymentHistoryViewController: UIBaseMenuViewController {
private let billPaymentService:BillPaymentServiceApiProtocol = BillPaymentServiceApi()
var lastDays = 30
var bills = [BillPaymentHistory]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
loadAccountHistoryServer(lastDays)
}
func configureTableView(){
// tableVIew
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.cellLayoutMarginsFollowReadableWidth = false
self.tableView.separatorColor = .clear
self.tableView.tableFooterView = UIView()
self.tableView.estimatedRowHeight = 100
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.register(UINib(nibName: BillPaymentHistoryCell.Identifier, bundle: nil), forCellReuseIdentifier: BillPaymentHistoryCell.Identifier)
}
func loadAccountHistoryServer(_ lastDays: Int){
self.showActivityIndicatory()
var enterpriseId = 0
if let enterprise = Session.sharedInstance.enterprise {
enterpriseId = enterprise.id
}
billPaymentService.getBillPayment(enterpriseId: enterpriseId,
lastDays: lastDays,
success: { [weak self] billsfromServer in
guard let strongSelf = self else {return }
strongSelf.hideActivityIndicatory()
strongSelf.bills = billsfromServer
strongSelf.tableView.reloadData()
}, failure: defaultFailureCallBack)
}
@IBAction func navegateToPaymentView(_ sender: Any) {
let navegationView = MainNavigationController(rootViewController: ManagerViewController.getPaymentViewController())
self.revealViewController().hideLeftView(animated: true)
self.revealViewController().setMain(navegationView, animated:true)
}
}
extension BillPaymentHistoryViewController: UITableViewDelegate, UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bills.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: BillPaymentHistoryCell.Identifier) as! BillPaymentHistoryCell
let bill = bills[indexPath.row]
cell.bill = bill
cell.defineBackgroundColor(byRowIndex: indexPath.row)
return cell
}
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
//
// return 82.0
//
// }
}
|
import XCTest
@testable import iOSAdapters
class PileListScreenTests: XCTestCase {
private var sut: PileListScreen!
private var controllerPresenter: ControllerPresenterSpy!
private var viewControllerCreator: ViewControllerCreatorSpy!
override func setUp() {
super.setUp()
controllerPresenter = ControllerPresenterSpy()
viewControllerCreator = ViewControllerCreatorSpy()
sut = PileListScreen(controllerPresenter, viewControllerCreator)
}
override func tearDown() {
controllerPresenter = nil
viewControllerCreator = nil
sut = nil
super.tearDown()
}
func test_present_presentViewController() {
sut.present()
XCTAssertEqual(controllerPresenter.addChildViewControllerCallCount, 1)
XCTAssertEqual(controllerPresenter.presentCallCount, 0)
}
func test_present_usesViewControllerFromfactory() {
sut.present()
XCTAssertTrue(controllerPresenter
.savedChildController === viewControllerCreator.testCreateController)
}
func test_present_didMove() {
sut.present()
XCTAssertEqual(viewControllerCreator
.testCreateController.didMoveCallCount, 1)
}
}
|
//
// HomeView.swift
// GetupApp
//
// Created by 神村亮佑 on 2020/07/05.
// Copyright © 2020 神村亮佑. All rights reserved.
//
import SwiftUI
import BottomBar_SwiftUI
import SwiftUICharts
struct HomeView: View {
@State private var pickerSelectedItem: Int = 1
@State private var dataPoints: [[CGFloat]] = [
[50, 100, 150, 100, 40, 10, 20],
[150, 100, 50, 10 ,200, 140, 10],
[10, 20, 30, 100, 30, 150, 10]
]
@State private var dayofweeks: [String] = [
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
]
var body: some View {
ZStack{
Color("appBackground").edgesIgnoringSafeArea(.all)
VStack{
Text("Calory Intake")
.foregroundColor(Color("title"))
.font(.system(size: 34))
.fontWeight(.heavy)
Picker(selection: $pickerSelectedItem, label: Text("")){
Text("Last Week").tag(0)
Text("This Week").tag(1)
Text("Fealings").tag(2)
}.pickerStyle(SegmentedPickerStyle())
.padding(.horizontal, 24)
HStack(spacing: 16){
BarView(value: dataPoints[pickerSelectedItem][0], day_of_week: dayofweeks[0])
BarView(value: dataPoints[pickerSelectedItem][1], day_of_week: dayofweeks[1])
BarView(value: dataPoints[pickerSelectedItem][2], day_of_week: dayofweeks[2])
BarView(value: dataPoints[pickerSelectedItem][3], day_of_week: dayofweeks[3])
BarView(value: dataPoints[pickerSelectedItem][4], day_of_week: dayofweeks[4])
BarView(value: dataPoints[pickerSelectedItem][5], day_of_week: dayofweeks[5])
BarView(value: dataPoints[pickerSelectedItem][6], day_of_week: dayofweeks[6])
}.padding(.top, 24)
.animation(.default)
}
}.cornerRadius(100)
}
}
struct BarView: View {
var value: CGFloat
var day_of_week: String
var body: some View{
VStack{
ZStack (alignment: .bottom){
Capsule().frame(width: 30, height: 200)
.foregroundColor(Color(#colorLiteral(red: 0.6229396462, green: 0.5232685804, blue: 0.9278500676, alpha: 1)))
Capsule().frame(width: 30, height: value)
.foregroundColor(.white)
}
Text(day_of_week).padding(.top, 8)
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
|
//
// ViewController.swift
// fingerSampleApp
//
// Created by Hisanori Ando on 2020/09/13.
// Copyright © 2020 Hisanori Ando. All rights reserved.
//
import UIKit
import CoreBluetooth
import CoreML
import Vision
//データ型にHexString変換メソッドを拡張する
extension Data {
/// A hexadecimal string representation of the bytes.
func hexEncodedString() -> String {
let hexDigits = Array("0123456789abcdef".utf16)
var hexChars = [UTF16.CodeUnit]()
hexChars.reserveCapacity(count * 2)
for byte in self {
let (index1, index2) = Int(byte).quotientAndRemainder(dividingBy: 16)
hexChars.append(hexDigits[index1])
hexChars.append(hexDigits[index2])
}
return String(utf16CodeUnits: hexChars, count: hexChars.count)
}
}
fileprivate func convertHex(_ s: String.UnicodeScalarView, i: String.UnicodeScalarIndex, appendTo d: [UInt8]) -> [UInt8] {
let skipChars = CharacterSet.whitespacesAndNewlines
guard i != s.endIndex else { return d }
let next1 = s.index(after: i)
if skipChars.contains(s[i]) {
return convertHex(s, i: next1, appendTo: d)
} else {
guard next1 != s.endIndex else { return d }
let next2 = s.index(after: next1)
let sub = String(s[i..<next2])
guard let v = UInt8(sub, radix: 16) else { return d }
return convertHex(s, i: next2, appendTo: d + [ v ])
}
}
extension String {
/// Convert Hexadecimal String to Array<UInt>
/// "0123".hex // [1, 35]
/// "aabbccdd 00112233".hex // 170, 187, 204, 221, 0, 17, 34, 51]
var hex : [UInt8] {
return convertHex(self.unicodeScalars, i: self.unicodeScalars.startIndex, appendTo: [])
}
/// Convert Hexadecimal String to Data
/// "0123".hexData /// 0123
/// "aa bb cc dd 00 11 22 33".hexData /// aabbccdd 00112233
var hexData : Data {
return Data(convertHex(self.unicodeScalars, i: self.unicodeScalars.startIndex, appendTo: []))
}
}
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
@IBOutlet weak var lblBLEStat: UILabel!
@IBOutlet weak var lblClassfierDate: UILabel!
@IBOutlet weak var lblClassfierResult: UILabel!
var centralManager: CBCentralManager!
var targetDevice: CBPeripheral!
static let BLE_UUID_PREFIX: String = "F000"
static let BLE_UUID_SUFFIX: String = "-0451-4000-B000-000000000000"
//指紋認証サービス
var STRING_SERVICE_FINGERPRINT: String = BLE_UUID_PREFIX + "1130" + BLE_UUID_SUFFIX
var UUID_SERVICE_FINGERPRINT: CBUUID!
//指紋認証情報キャラクタリスティック
var STRING_CHARACTERISTIC_FINGERPRINT_DATA1: String = BLE_UUID_PREFIX + "1131" + BLE_UUID_SUFFIX
var STRING_CHARACTERISTIC_FINGERPRINT_DATA2: String = BLE_UUID_PREFIX + "1132" + BLE_UUID_SUFFIX
var STRING_CHARACTERISTIC_FINGERPRINT_DATA3: String = BLE_UUID_PREFIX + "1133" + BLE_UUID_SUFFIX
var STRING_CHARACTERISTIC_FINGERPRINT_EVTDETECT: String = BLE_UUID_PREFIX + "1134" + BLE_UUID_SUFFIX
//ドアロック開錠サービス
var STRING_SERVICE_DOORLOCK: String = BLE_UUID_PREFIX + "1140" + BLE_UUID_SUFFIX
var UUID_SERVICE_DOORLOCK: CBUUID!
//ロック状態キャラクタリスティック
var STRING_CHARACTERISTIC_FDORRLOCK_STATE: String = BLE_UUID_PREFIX + "1141" + BLE_UUID_SUFFIX
var bWriteRequesting : Bool = false
@IBAction func btnScan(_ sender: Any) {
var nStat = 90
lblBLEStat.text = "Scanning...."
DispatchQueue.global().async {
nStat = self.startScan(timeOut:5000)
print("End of Scan (code:\(nStat))")
DispatchQueue.main.async {
if(nStat == 0){
self.lblBLEStat.text = "Found!!"
} else {
self.lblBLEStat.text = "(No Connector)"
}
}
}
}
@IBAction func btnConnect(_ sender: Any) {
if(bFoundDevice == true){
connectBle()
}
}
@IBAction func btnDisConnect(_ sender: Any) {
disconnectBle()
}
@IBAction func btnLockForceOpen(_ sender: Any) {
let value: [UInt8] = [0x01]
targetDevice.writeValue(Data(value), for: DOORLOCK_CHARA_STATE!, type: CBCharacteristicWriteType.withResponse)
}
@IBAction func btnLockForceClose(_ sender: Any) {
let value: [UInt8] = [0x02]
targetDevice.writeValue(Data(value), for: DOORLOCK_CHARA_STATE!, type: CBCharacteristicWriteType.withResponse)
}
private var bScaning:Bool = false
private var bFoundDevice:Bool = false
private var isConnected : Bool = false
//すきゃん開始
public func startScan(timeOut:Int)->Int{
var nStat :Int = 99
print("begin to scan ...")
//isConnected = false
targetDevice = nil
//他のスキャンもキャンセルさせる
bScaning = false
//スキャン停止
centralManager?.stopScan()
//スキャン開始
centralManager.scanForPeripherals(withServices: nil)
var cntTimeOut = 0
//スキャン中
bScaning = true
while true {
cntTimeOut = cntTimeOut + 100
//一定時間待つ
Thread.sleep(forTimeInterval: 0.1)
if(cntTimeOut > timeOut){
nStat = 90
break
} else if(bScaning == false){
nStat = 10//スキャンキャンセル
break
} else if(self.bFoundDevice == true){
nStat = 0
break
}
//スキャン停止
centralManager?.stopScan()
}
bScaning = false
return nStat
}
public func connectBle(){
centralManager.stopScan()
if(targetDevice != nil){
print("Try Connect")
if(isConnected == false){
//targetDevice
centralManager.connect(targetDevice, options: nil)
}
}
}
public func disconnectBle(){
if(targetDevice != nil){
centralManager.cancelPeripheralConnection(targetDevice)
}
}
// BT2コネクタ探索結果を受信ハンドラ(scanStartでのコールバック)
public func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String: Any],
rssi RSSI: NSNumber) {
print("pheripheral.name: \(String(describing: peripheral.name))")
print("advertisementData:\(advertisementData)")
print("RSSI: \(RSSI)")
print("peripheral.identifier.uuidString: \(peripheral.identifier.uuidString)\n")
var name : String ;
name = String(describing: peripheral.name)
if name.contains("Project Zero R2") { // -> true
print("Found!!")
targetDevice = peripheral
bFoundDevice = true
}
}
//BT2接続失敗時ハンドラ
public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("Connect failed...")
}
// BT2コネクタ接続済みハンドラ(connectBt後にコールバックする)
public func centralManager(_ central: CBCentralManager,
didConnect peripheral: CBPeripheral) {
print("connected")
isConnected = true
//接続成功したら利用するサービスUUIDを検索する
peripheral.delegate = self
//peripheral.discoverServices(nil) //全てのサービス検索する
peripheral.discoverServices(
[UUID_SERVICE_FINGERPRINT,UUID_SERVICE_DOORLOCK])//指定したサービスのみ検索する
}
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard let services = peripheral.services else{
print("error")
return
}
print("\(services.count)個のサービスを発見。\(services)")
if(services.count > 0){
services.forEach {
//発見したサービスに属するキャラクタリスティックを探す
peripheral.discoverCharacteristics(nil, for:$0)
}
}
}
var FINGERPRT_CHARA_DATA1:CBCharacteristic? = nil
var FINGERPRT_CHARA_DATA2:CBCharacteristic? = nil
var FINGERPRT_CHARA_DATA3:CBCharacteristic? = nil
var FINGERPRT_CHARA_EVTDETECT:CBCharacteristic? = nil
var DOORLOCK_CHARA_STATE:CBCharacteristic? = nil
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let characteristics = service.characteristics {
print("\(characteristics.count)個のキャラクタリスティックを発見。\(characteristics)")
if(characteristics.count > 0){
//「セッティングサービス」のキャラクタリスティックを保持する
if(service.uuid.uuidString == STRING_SERVICE_FINGERPRINT){
characteristics.forEach {
if($0.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_DATA1){
FINGERPRT_CHARA_DATA1 = $0
} else if($0.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_DATA2){
FINGERPRT_CHARA_DATA2 = $0
} else if($0.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_DATA3){
FINGERPRT_CHARA_DATA3 = $0
} else if($0.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_EVTDETECT){
targetDevice.setNotifyValue(true,for:$0)
FINGERPRT_CHARA_EVTDETECT = $0
}
}
}
else if(service.uuid.uuidString == STRING_SERVICE_DOORLOCK){//ドア開錠サービス
characteristics.forEach {
if($0.uuid.uuidString == STRING_CHARACTERISTIC_FDORRLOCK_STATE){
DOORLOCK_CHARA_STATE = $0
}
}
}
}
}
}
public func peripheral(_ peripheral: CBPeripheral,
didWriteValueFor characteristic: CBCharacteristic,error: Error?)
{
if let error = error {
print("Failed... error: \(error)")
return
}
print("ドア状態セット完了")
//
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0, execute: {
print("通知再度有効化")
self.bWriteRequesting = false
})
}
var strFingerCharData1 :String = ""
var strFingerCharData2 :String = ""
var strFingerCharData3 :String = ""
//キャラクタリスティック読み込み完了コールバックイベント
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic,error: Error?)
{
if let error = error {
print("Failed... error: \(error)")
return
}
if(bWriteRequesting == true){
return
}
//指紋認証サービスの値取得ブロック
if(characteristic.service.uuid.uuidString == STRING_SERVICE_FINGERPRINT){
if(characteristic.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_EVTDETECT){
print("指紋認証イベント検知")
//DATA1〜DATA3の情報を取得する
strFingerCharData1 = ""
strFingerCharData2 = ""
strFingerCharData3 = ""
targetDevice.readValue(for:FINGERPRT_CHARA_DATA1!)
targetDevice.readValue(for:FINGERPRT_CHARA_DATA2!)
targetDevice.readValue(for:FINGERPRT_CHARA_DATA3!)
} else {
let strData :String = Data(characteristic.value!).hexEncodedString()
if(characteristic.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_DATA1){
strFingerCharData1 = strData
}
else if(characteristic.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_DATA2){
strFingerCharData2 = strData
}
else if(characteristic.uuid.uuidString == STRING_CHARACTERISTIC_FINGERPRINT_DATA3){
strFingerCharData3 = strData
}
//すべてのデータ取得が完了したら結合して認証を行う
if(strFingerCharData1 != ""
&& strFingerCharData2 != ""
&& strFingerCharData3 != ""){
let strTotalData:String = strFingerCharData1 + strFingerCharData2 + strFingerCharData3
let int8TotalData = strTotalData.hex
// print(strTotalData)
// print(byteTotalData)
var numIntegers: [Double] = []
for val8 in int8TotalData {
numIntegers.append(Double(val8)/255.0)
}
let mlInputData = convertToMLArray(numIntegers)
print("COnverted")
print(mlInputData)
var resultFinger :Int = 0
do {
let output = try converted().prediction(input: mlInputData)
print("FingerIndex=")
print(output.classLabel)
resultFinger = Int(output.classLabel)
//
var doorVal: [UInt8] = [0x01]
if(output.classLabel == 2 ){
doorVal[0] = 1 //2の場合はNGにする
} else{
doorVal[0] = 2//それ以外はOK
}
if(DOORLOCK_CHARA_STATE != nil){
//書き込み後はしばらく変化値をみないようにする
bWriteRequesting = true
let data = NSData(bytes: doorVal, length: 1)
targetDevice.writeValue(data as Data, for: DOORLOCK_CHARA_STATE!,
type: CBCharacteristicWriteType.withResponse)
}
//画面に状態検知&変化を表示する
DispatchQueue.main.async {
let dt = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "yyyy/MM/dd H:m:s", options: 0, locale: Locale(identifier: "ja_JP"))
print(dateFormatter.string(from: dt))
self.lblClassfierDate.text = dateFormatter.string(from: dt)
let strResult :String = doorVal[0] == 1 ? "NG":"OK"
self.lblClassfierResult.text = String(format: "%@ (Finger %d)", strResult, resultFinger )
}
} catch {
// エラー処理
}
}
}
}
}
//デバイスと切断したときに呼ばれるコールバック
public func centralManager(_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?){
//targetDevice = nil
print("切断しました")
bFoundDevice = false
isConnected = false
}
// stop scan
public func stopScan() {
if(centralManager != nil){
//スキャンキャンセルさせる
bScaning = false
centralManager.stopScan()
print("Stop Scan")
} else {
print("Not initialized yet")
}
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch (central.state) {
case .unknown:
print(".unknown")
break
case .resetting:
print(".resetting")
break
case .unsupported:
print(".unsupported")
break
case .unauthorized:
print(".unauthorized")
break
case .poweredOff:
print(".poweredOff")
break
case .poweredOn:
print(".poweredOn")
break
@unknown default:
print("A previously unknown central manager state occurred")
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
//UUIDを生成する
UUID_SERVICE_FINGERPRINT = CBUUID(string: STRING_SERVICE_FINGERPRINT)
UUID_SERVICE_DOORLOCK = CBUUID(string: STRING_SERVICE_DOORLOCK)
}
func convertToMLArray(_ input: [Double]) -> MLMultiArray {
let mlArray = try? MLMultiArray(shape: [256], dataType: MLMultiArrayDataType.double)
for i in 0..<input.count {
mlArray?[i] = NSNumber(value: input[i])
}
return mlArray!
}
}
|
//
// RoundedShadowImageView.swift
// VisionApp
//
// Created by kanchanproseth on 12/1/17.
// Copyright © 2017 Norton. All rights reserved.
//
import UIKit
class RoundedShadowImageView: UIImageView {
override func awakeFromNib() {
self.layer.shadowColor = UIColor.darkGray.cgColor
self.layer.borderWidth = 2
self.layer.borderColor = UIColor.white.cgColor
self.layer.shadowRadius = 15
self.layer.shadowOpacity = 0.75
self.layer.cornerRadius = 5
self.layer.masksToBounds = true
}
}
|
//
// CustomTitleLabel.swift
// The Danya App
//
// Created by Gershy Lev on 9/14/17.
// Copyright © 2017 Gershy Lev. All rights reserved.
//
import UIKit
class CustomTitleLabel: UILabel {
init(text: String) {
super.init(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
self.font = UIFont(name: "Marker Felt", size: 25.0)
self.textColor = UIColor(red: 128/355, green: 0/355, blue: 255/355, alpha: 1.0)
self.textAlignment = .center
self.text = text
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
//
// BaseAlertViewController.swift
// StylePizza
//
// Created by MACOS on 11/24/17.
// Copyright © 2017 MACOS. All rights reserved.
//
import UIKit
class BaseAlertViewController: UIViewController {
// MARK: Define controls
internal let viewBackground: UIView = {
let view = UIView()
view.backgroundColor = Theme.shared.alertBGColor
view.alpha = 0
return view
}()
// MARK: This function is a default initialization function
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.modalPresentationStyle = .overFullScreen
self.modalTransitionStyle = .crossDissolve
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupViewBackground()
self.setupView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Setup layout
private func setupViewBackground() {
self.view.addSubview(self.viewBackground)
self.viewBackground.snp.makeConstraints { (make) in
make.top.bottom.left.right.equalToSuperview()
}
let tapGesture = UITapGestureRecognizer(
target: self,
action: #selector(dismissAlert)
)
self.viewBackground.addGestureRecognizer(tapGesture)
}
func setupView() {}
@objc func dismissAlert() {
self.dismiss(animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
UIView.animate(withDuration: 0.3) {
self.viewBackground.alpha = 1
}
}
}
|
//
// IPhoneGridTests.swift
// florafinder
//
// Created by Andrew Tokeley on 24/03/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import XCTest
@testable import florafinder
class IPhoneGridTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRatioOfDerivedGridMatchesPhoneRatio() {
let grid = IPhoneGrid(frame: CGRect(origin: CGPointZero, size: CGSize(width: 100, height: 300)), rows: 2, columns: 3)
let derivedRatio = grid.phoneRectSize.width/grid.phoneRectSize.height
let phoneRatio = Units.sizeOfPhoneInCentimetres.width/Units.sizeOfPhoneInCentimetres.height
XCTAssertTrue(derivedRatio == phoneRatio)
}
// func testHeightConstrained()
// {
// let grid = IPhoneGrid(frame: CGRect(origin: CGPointZero, size: CGSize(width: Units.sizeOfPhoneInCentimetres.width + 100, height: Units.sizeOfPhoneInCentimetres.height)), rows: 3, columns: 2)
//
// // phone grids should be constrained to the height of the frame
// let totalPhoneGridHeights = grid.phoneRectSize.height * 3
//
// XCTAssertTrue(totalPhoneGridHeights == Units.sizeOfPhoneInCentimetres.height)
// }
//
// func testWidthConstrained()
// {
// let grid = IPhoneGrid(frame: CGRect(origin: CGPointZero, size: CGSize(width: 100, height: 300)), rows: 1, columns: 4)
//
// // phone grids should be constrained to the height of the frame
// let totalPhoneGridWidths = grid.phoneRectSize.width * 4
// print(totalPhoneGridWidths)
//
// XCTAssertTrue(totalPhoneGridWidths == 100)
// }
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
|
//
// Pokemon.swift
// Pokedex
//
// Created by Thi Danny on 12/23/15.
// Copyright © 2015 Spawn Camping Panda. All rights reserved.
//
struct PokemonURLs {
static let base = "http://pokeapi.co"
static let pokemon = "/api/v1/pokemon/"
}
import Foundation
class Pokemon {
private(set) var pokemonName: String!
private(set) var pokedexID: Int!
var desc: String!
var type: String!
var attack: String!
var defense: String!
var height: String!
var weight: String!
var nextEvolutionName: String!
var nextEvolutionId: String!
var nextEvolutionLevel: String!
private(set) var pokemonURL: String!
init(name: String, id: Int) {
pokemonName = name
pokedexID = id
pokemonURL = "\(PokemonURLs.base)\(PokemonURLs.pokemon)\(pokedexID)/"
}
} |
//
// StationTableViewCell.swift
// SurfSchoolRadio
//
// Created by Nastya on 4/22/20.
// Copyright © 2020 Surf. All rights reserved.
//
import UIKit
class StationTableViewCell: UITableViewCell {
@IBOutlet weak var stationImageView: UIImageView!
@IBOutlet weak var stationNameLabel: UILabel!
@IBOutlet weak var stationDescLabel: UILabel!
var downloadTask: URLSessionDownloadTask?
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
let selectedView = UIView(frame: CGRect.zero)
selectedView.backgroundColor = UIColor(red: 78/255, green: 82/255, blue: 93/255, alpha: 0.6)
selectedBackgroundView = selectedView
}
func configureStationCell (station: RadioStation) {
stationNameLabel.text = station.name
stationDescLabel.text = station.desc
// DispatchQueue.main.async {
// if let url = URL(string: station.imageURL) {
// if let data = try? Data(contentsOf: url) {
// self.stationImageView.image = UIImage(data: data)
//
// }
// }
// }
let imageURL = station.imageURL as NSString
if imageURL.contains("http"), let url = URL(string: station.imageURL) {
stationImageView.loadImageWithURL(url: url) { (image) in
}
} else if imageURL != "" {
stationImageView.image = UIImage(named: imageURL as String)
} else {
stationImageView.image = UIImage(named: "stationImage")
}
}
override func prepareForReuse() {
super.prepareForReuse()
downloadTask?.cancel()
downloadTask = nil
stationNameLabel.text = nil
stationDescLabel.text = nil
stationImageView.image = nil
}
}
extension UIImageView {
func loadImageWithURL(url: URL, callback: @escaping (UIImage) -> ()) {
let session = URLSession.shared
let downloadTask = session.downloadTask(with: url, completionHandler: {
[weak self] url, response, error in
if error == nil && url != nil {
if let data = NSData(contentsOf: url!) {
if let image = UIImage(data: data as Data) {
DispatchQueue.main.async(execute: {
if let strongSelf = self {
strongSelf.image = image
callback(image)
}
})
}
}
}
})
downloadTask.resume()
}
}
|
//
// RestApiManager.swift
// BalancedGym
//
// Created by Pablou on 10/15/17.
// Copyright © 2017 Pablou. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
class RestApiManager {
static let sharedInstance = RestApiManager()
let baseURL = Bundle.main.infoDictionary!["BASE_URL"] as! String
//let baseURL = "https://balanced-gym.herokuapp.com"
//let baseURL2 = "http://localhost:5000"
func getRoutines(completionHandler: @escaping ([Routine]) -> Void) {
Alamofire.request("\(baseURL)/routine").responseArray { (response : DataResponse<[Routine]>) in
if let routines = response.result.value {
completionHandler(routines)
} else {
completionHandler([])
}
}
}
func getRoutine(routineId: String, completionHandler: @escaping (Routine) -> Void) {
Alamofire.request("\(baseURL)/routine/\(routineId)").responseObject {
(response: DataResponse<Routine>) in
let routine = response.result.value
completionHandler(routine!)
}
}
func getMuscleGroup(muscleGroup: String, routineId: String, completionHandler: @escaping (GroupedExercise) -> Void) {
let parameters: Parameters = [
"routineId": routineId,
"muscleGroup": muscleGroup
]
Alamofire.request("\(baseURL)/muscleGroup", parameters: parameters).responseObject {
(response: DataResponse<GroupedExercise>) in
if let group = response.result.value {
completionHandler(group)
}
}
}
// func getExercise(exercise: Exercise, completionHandler: @escaping (Exercise) -> Void) {
// Alamofire.request("\(baseURL)/exercise/\(exercise.id)").responseObject {
// (response: DataResponse<Exercise>) in
// let exercise = response.result.value
// completionHandler(exercise!)
// }
// }
func updateExercise(exercise: Exercise ) {
let series = exercise.series.map{ serie in
return ["_id": serie.id, "reps": serie.reps, "weight": serie.weight]}
let parameters: Parameters = [
"series": series
]
let id = exercise.id
let url = "\(baseURL)/exercise/\(id)"
Alamofire.request(url, method: .patch, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
//debugPrint(response)
//if let json = response.result.value {
//print("JSON: \(json)")
//}
}
}
func updateSerie(serie: Serie, completionHandler: @escaping () -> Void ) {
let reps : Int = serie.reps
let weight: Float = serie.weight
let parameters: Parameters = [
"reps": reps, "weight": weight
]
let id = serie.id
let url = "\(baseURL)/serie/\(id)"
Alamofire.request(url, method: .patch, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
//debugPrint(response)
//if let json = response.result.value {
// print("JSON: \(json)")
//}
completionHandler();
}
}
func deleteSerie(serie: Serie, completionHandler: @escaping () -> Void) {
let id = serie.id
let url = "\(baseURL)/serie/\(id)"
Alamofire.request(url, method: .delete).responseJSON { response in
//if let result = response.result.value {
completionHandler()
//}
}
}
func addSerie(exercise: Exercise, completionHandler: @escaping (Serie) -> Void) {
let id = exercise.id
let url = "\(baseURL)/newSerie/\(id)"
Alamofire.request(url, method: .post).responseObject { (response : DataResponse<Serie>) in
// print(response)
//to get status code
if let serie : Serie = response.result.value {
//let serie = self.jsonConverter.getSerie(jsonSerie: result as! NSDictionary)
completionHandler(serie)
}
}
}
}
|
import Foundation
import SwiftLanguageServerLib
/*
let reader = try FileReader(filepath: "test.txt")
var bytes: [UInt8]? = try reader.readLine()
while let b = bytes {
print(String(bytes: b, encoding: .utf8))
bytes = try reader.readLine()
}*/
print("*** SourceKit ***")
let client = try JSONDecoder().decode(ClientCapabilities.self, from: "{}".data(using: .utf8)!)
let server = LanguageServer(clientCapabilities: client)
print("Yay")
let path = "file:///somefile.swift"
try print(server.generateDiagnostics(for: path))
|
//
// ViewExtensions.swift
// CovidUI
//
// Created by Daniel Plata on 15/04/2020.
// Copyright © 2020 silverapps. All rights reserved.
//
import Foundation
import UIKit
import SwiftUI
extension View {
func navigationBarColor(_ backgroundColor: UIColor?) -> some View {
self.modifier(NavigationBarModifier(backgroundColor: backgroundColor))
}
}
|
//
// ViewController.swift
// Wallpaper_app
//
// Created by Sneh Patel on 4/2/20.
// Copyright © 2020 Sneh Patel. All rights reserved.
//
import UIKit
class WallpaperTabViewController: UIViewController {
var wallpaperUrl: URL? {
didSet{
firstWallpaper.image = nil
if view.window != nil {
fetchImage()
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if firstWallpaper.image == nil{
fetchImage()
}
}
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var firstWallpaper: UIImageView!
//gets the image from the url
private func fetchImage() {
if let url = wallpaperUrl {
spinner.startAnimating()
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
let urlContents = try? Data(contentsOf: url)
DispatchQueue.main.async {
if let imageData = urlContents, url == self?.wallpaperUrl {
self?.firstWallpaper.image = UIImage(data: imageData)
self?.spinner.stopAnimating()
}
}
}
}
}
//sets a temporary image while the main thing loads
override func viewDidLoad() {
super.viewDidLoad()
if wallpaperUrl == nil {
wallpaperUrl = ImageURLs.temporaryImage
}
}
//saves the image
@IBAction func savePhoto(_ sender: Any) {
let imageSaver = ImageSaver()
if let inputImage = firstWallpaper.image {
imageSaver.writeToPhotoAlbum(image: inputImage)
let alertController = UIAlertController(title: "Saved!", message: "Your Wallpaper is saved to Photos.", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
}
|
//
// EventModel.swift
// YourCityEvents
//
// Created by Yaroslav Zarechnyy on 11/24/19.
// Copyright © 2019 Yaroslav Zarechnyy. All rights reserved.
//
import Foundation
struct EventsModelResponse: Codable {
let events: [EventModel]
}
struct EventModelResponse: Codable {
let event: EventModel
}
struct EventModel: Codable {
var id: String? = nil
var title: String
var location: CityModel
var description: String?
var owner: UserModel?
var imageUrl: String?
var date: String
var detailLocation: String
var visitors: [UserModel]?
var price: Int
}
struct CreateEventModel: Codable {
var title: String
var description: String
var detailLocation: String
var imageArray: String?
var price: Int
var date: String
}
extension EndpointCollection {
static let getEvents = Endpoint(method: .GET, pathEnding: "Event")
static let createEvent = Endpoint(method: .POST, pathEnding: "Event")
static func deleteEvent(with id: String) -> Endpoint {
return Endpoint(method: .DELETE, pathEnding: "Event/\(id)")
}
}
|
/*
* ImageScrollView.swift
* Created by Kajetan Dąbrowski on 25/03/2018.
*
* iOS Level Up 2018
* Copyright 2018 DaftMobile Sp. z o. o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
class ImageScrollView: UIScrollView {
var index: Int
var image: UIImage? {
get { return imageView.image }
set {
imageView.image = newValue
resize()
}
}
private let imageView: UIImageView
init(image: UIImage?, index: Int) {
self.index = index
self.imageView = UIImageView(image: image)
super.init(frame: CGRect(origin: .zero, size: image?.size ?? .zero))
addSubview(imageView)
self.delegate = self
resize()
minimumZoomScale = 1.0
maximumZoomScale = 4.0
}
override var frame: CGRect {
didSet {
resize()
}
}
private func resize() {
guard let image = image else { return }
zoomScale = 1.0
let widthProportion = bounds.width / image.size.width
let heightProportion = bounds.height / image.size.height
let proportion = min(widthProportion, heightProportion)
imageView.frame.size.width = proportion * image.size.width
imageView.frame.size.height = proportion * image.size.height
contentSize = imageView.frame.size
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame.origin.x = imageView.frame.width < bounds.width ? (bounds.width - imageView.frame.width) * 0.5 : 0
imageView.frame.origin.y = imageView.frame.height < bounds.height ? (bounds.height - imageView.frame.height) * 0.5 : 0
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
}
extension ImageScrollView: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView }
}
|
//
// ShowAllTableTableViewController.swift
// UBox
//
// Created by Liam He on 2/26/18.
// Copyright © 2018 Liam He. All rights reserved.
//
import UIKit
class showAll: UITableViewController{
var jsonArray = [NSDictionary]()
var swipeIDX = 0
override func viewDidLoad() {
super.viewDidLoad()
//getting API calls
let apiURL = URL(string: "http://192.168.1.113:8000/api/lunchbox/")
let task = URLSession.shared.dataTask(with: apiURL!, completionHandler: {
data, response, error in
do {
let json = try JSONSerialization.jsonObject(with: data!)
self.jsonArray = json as! [NSDictionary]
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch{
print("ERROR", error)
}
})
task.resume()
}//view did load
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jsonArray.count
}//# of rows in section
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customCell
cell.scrollView.delegate = cell
let imgArray = jsonArray[indexPath.row]["images"] as? [NSDictionary]
cell.dish.text = jsonArray[indexPath.row]["title"] as? String
let scrollViewWidth:CGFloat = cell.scrollView.frame.width
let scrollViewHeight:CGFloat = cell.scrollView.frame.height
var startX :CGFloat = 0
cell.pageControll.currentPage = 0
cell.pageControll.numberOfPages = imgArray!.count
cell.scrollView.contentSize = CGSize(width: scrollViewWidth * CGFloat(imgArray!.count), height:scrollViewHeight)
cell.scrollView.subviews.forEach({ $0.removeFromSuperview() })
for index in 0 ..< imgArray!.count {
let img = UIImageView(frame: CGRect(x:startX, y:0, width: scrollViewWidth, height: scrollViewHeight))
cell.scrollView.addSubview(img)
startX += scrollViewWidth
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
let urlStr = "\(imgArray![index]["image"] ?? "No Image Found")"
img.image = UIImage()
URLSession.shared.dataTask(with: NSURL(string: urlStr)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async(execute: { () -> Void in
img.image = UIImage(data:data!)
})
}).resume()
}
return cell
}
}
|
//
// SecondViewController.swift
// TalentNearMe
//
// Created by M.A.D. Crew. on 21/10/2016.
// Copyright © 2016 M.A.D. Crew. All rights reserved.
//
import UIKit
class ChatListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var avengers = ["Thor", "Hulk", "Iron Man", "captain US", "hot girl"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return avengers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
print(indexPath.row)
cell.textLabel?.text = avengers[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "ourSegue", sender: avengers[indexPath.row])
}
}
|
//
// PresentTrasition.swift
// VCTransitionTest
//
// Created by daoquan on 2017/11/21.
// Copyright © 2017年 deerdev. All rights reserved.
//
import UIKit
class PresentTrasition: NSObject, UIViewControllerAnimatedTransitioning {
/// 动画的实现
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// 过场view
let containView = transitionContext.containerView
// 获取过场的 源控制器(view) 和 目的控制器(view)
guard let toView = transitionContext.view(forKey: .to),
// let toVC = transitionContext.viewController(forKey: .to),
// let fromVC = transitionContext.viewController(forKey: .from),
let fromView = transitionContext.view(forKey: .from)
else { return }
// 获取过场时间
let durationTime = transitionDuration(using: transitionContext)
// 根据不同的过程 加载动画
containView.addSubview(toView)
toView.alpha = 0
let originTransform = toView.layer.transform
toView.layer.transform = CATransform3DMakeRotation(CGFloat(Double.pi / 2), 0, 1, 0)
// 向上渐变加载
UIView.animate(withDuration: durationTime, animations: {
toView.alpha = 1
toView.layer.transform = originTransform
}, completion: { (_) in
// 结束转场
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
/// 动画的过渡时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.35
}
}
|
//
// Ladder.swift
// SnakeAndLadder
//
// Created by Sudhanshu Sudhanshu on 28/08/20.
//
import UIKit
class Ladder {
private let start: Int
private let end: Int
init(start: Int, end: Int) {
self.start = start
self.end = end
}
func getStart() -> Int {
start
}
func getEnd() -> Int {
end
}
}
extension Ladder: Hashable {
func hash(into hasher: inout Hasher) {
}
static func == (lhs: Ladder, rhs: Ladder) -> Bool {
return lhs.start == rhs.start && lhs.end == rhs.end
}
}
|
//
// TollFreeDTO.swift
// VitelityClient
//
// Created by Jorge Enrique Dominguez on 10/10/18.
// Copyright © 2018 sigmatric. All rights reserved.
//
import Foundation
public struct TollFreeDTO {
public let number: String
}
|
//
// Programming.swift
// SearchProject
//
// Created by DUCH Chamroeun on 10/28/19.
// Copyright © 2019 DUCH Chamroeurn. All rights reserved.
//
import Foundation
struct Programming: Codable {
let id: Int
let title: String
let description: String
let logo: String?
}
|
//
// APIParameters+Filtering.swift
//
//
// Created by Vladislav Fitc on 07/07/2020.
//
import Foundation
import AlgoliaSearchClient
extension APIParameters {
//MARK: - Filtering
func filtering() {
func filters() {
/*
query.filters = "attribute:value [AND | OR | NOT](#boolean-operators) attribute:value"
"numeric_attribute [= | != | > | >= | < | <=](#numeric-comparisons) numeric_value"
"attribute:lower_value [TO](#numeric-range) higher_value"
"[facetName:facetValue](#facet-filters)"
"[_tags](#tag-filters):value"
"attribute:value"
*/
func applyFilters() {
let query = Query("query")
.set(\.filters, to: "(category:Book OR category:Ebook) AND _tags:published")
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func applyAllFilters() {
let query = Query("query")
.set(\.filters, to: "available = 1 AND (category:Book OR NOT category:Ebook) AND _tags:published AND publication_date:1441745506 TO 1441755506 AND inStock > 0 AND author:\"John Doe\"")
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func escapeSpaces() {
let query = Query("query")
.set(\.filters, to: "category:'Books and Comics'")
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func escapeKeywords() {
let query = Query("query")
.set(\.filters, to: "keyword:'OR'")
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func escapeSingleQuotes() {
let query = Query("query")
.set(\.filters, to: "content:'It\\'s a wonderful day'")
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func escapeDoubleQuotes() {
let query = Query("query")
.set(\.filters, to: "content:'She said \"Hello World\"'")
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func facetFilters() {
/*
query.facetFilters = [
"attribute:value", // (single string)
// attribute1:value AND attribute2:value (multiple strings)
"attribute1:value", "attribute2:value"
// attribute1:value OR attribute2:value (multiple strings within an array)
.or("attribute1:value", "attribute2:value"),
// (attribute1:value OR attribute2:value) AND attribute3:value (combined strings and arrays)
.or("attribute1:value", "attribute2:value"), "attribute3:value",
...
]
*/
func set_single_string_value() {
let query = Query("query")
.set(\.facetFilters, to: [
"category:Book"
]
)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func set_multiple_string_values() {
let query = Query("query")
.set(\.facetFilters, to: [
"category:Book", "author:John Doe"
]
)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func set_multiple_values_within_array() {
let query = Query("query")
.set(\.facetFilters, to: [
.or("category:Book", "category:Movie")
]
)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func combine_arrays_and_strings() {
let query = Query("query")
.set(\.facetFilters, to: [
.or("category:Book", "category:Movie"), "author:John Doe"
]
)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func optionalFilters() {
/*
optionalFilters = [
"attribute:value",
.or("attribute1:value", "attribute2:value")
]
*/
func applyFilters() {
let query = Query()
.set(\.optionalFilters, to: ["category:Book", "author:John Doe"])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func applyNegativeFilters() {
let query = Query()
.set(\.optionalFilters, to: ["category:Book", "author:-John Doe"])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func numericFilters() {
/*
numericFilters = [
"numeric_attribute [= | != | > | >= | < | <=](#numeric-comparisons) numeric_value",
"attribute:lower_value [TO](#numeric-range) higher_value"
]
*/
func applyNumericFilters() {
let query = Query("query")
.set(\.numericFilters, to: [
.or("inStock = 1", "deliveryDate < 1441755506"),
"price < 1000"
])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func tagFilters() {
/*
tagFilters = [
"value",
// value1 OR value2
.or("value1", "value2"),
// (value1 OR value2) AND value3
.or("value1", "value2"), "value3",
...
]
*/
func applyTagFilters() {
let query = Query("query").set(\.tagFilters, to: [
.or("Book", "Movie"),
"SciFi"
])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func sumOrFiltersScore() {
/*
sumOrFiltersScores = true|false
*/
let query = Query("query")
.set(\.sumOrFiltersScores, to: true)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
}
|
@testable import Vapor
import XCTest
final class URLEncodedFormSerializerTests: XCTestCase {
func testPercentEncoding() throws {
let form: [String: URLEncodedFormData] = ["aaa]": "+bbb ccc"]
let data = try URLEncodedFormSerializer().serialize(form)
XCTAssertEqual(data, "aaa%5D=%2Bbbb%20%20ccc")
}
func testPercentEncodingWithAmpersand() throws {
let form: [String: URLEncodedFormData] = ["aaa": "b%26&b"]
let data = try URLEncodedFormSerializer().serialize(form)
XCTAssertEqual(data, "aaa=b%2526&b")
}
func testNested() throws {
let form: [String: URLEncodedFormData] = ["a": ["b": ["c": ["d": ["hello": "world"]]]]]
let data = try URLEncodedFormSerializer().serialize(form)
XCTAssertEqual(data, "a[b][c][d][hello]=world")
}
}
|
//
// HTTPClass.swift
import Foundation
/// This is a list of Hypertext Transfer Protocol (HTTP) response status codes.
/// It includes codes from IETF internet standards, other IETF RFCs, other specifications, and some additional commonly used codes.
/// The first digit of the status code specifies one of five classes of response; an HTTP client must recognise these five classes at a minimum.
enum HTTPStatusCode: Int, Error {
/// The response class representation of status codes, these get grouped by their first digit.
enum ResponseType {
/// - success: This class of status codes indicates the action requested by the client was received, understood, accepted, and processed successfully.
case success
/// - clientError: This class of status code is intended for situations in which the client seems to have erred.
case clientError
/// serverError: This class of status code indicates the server failed to fulfill an apparently valid request.
case clientErrorValidations
/// - serverError: This class of status code indicates the server failed to fulfill an apparently valid request.
case serverError
/// - undefined: The class of the status code cannot be resolved.
case undefined
}
/// - ok: Standard response for successful HTTP requests.
case ok = 200
case notAcceptable = 406
/// - unprocessableEntity: The request was well-formed but was unable to be followed due to semantic errors.
case unprocessableEntity = 422
/// - internalServerError: A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
case internalServerError = 500
/// The class (or group) which the status code belongs to.
var responseType: ResponseType {
switch self.rawValue {
case 200:
return .success
case 406:
return .clientErrorValidations
case 422:
return .clientError
case 500:
return .serverError
default:
return .undefined
}
}
}
extension HTTPURLResponse {
var status: HTTPStatusCode? {
return HTTPStatusCode(rawValue: statusCode)
}
}
|
import UIKit
public protocol CoasterToolerbarDelegate {
func forwardPressed()
func rightPressed()
func leftPressed()
func undoPressed()
}
public class CoasterToolbar: UIView {
public var delegate: CoasterToolerbarDelegate?
var forwardButton: UIImageView!
var rightButton: UIImageView!
var leftButton: UIImageView!
var undoButton: UIImageView!
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not using IB")
}
func initialize() {
forwardButton = UIImageView(image: UIImage.init(named: "Forward"))
forwardButton.frame = CGRect(x: 94, y: 7, width: 12, height: 17)
forwardButton.isUserInteractionEnabled = true
forwardButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(forwardPressed)))
rightButton = UIImageView(image: UIImage.init(named: "Right"))
rightButton.frame = CGRect(x: 116, y: 6, width: 17, height: 17)
rightButton.isUserInteractionEnabled = true
rightButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rightPressed)))
leftButton = UIImageView(image: UIImage.init(named: "Left"))
leftButton.frame = CGRect(x: 67, y: 6, width: 17, height: 17)
leftButton.isUserInteractionEnabled = true
leftButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(leftPressed)))
undoButton = UIImageView(image: UIImage.init(named: "undo"))
undoButton.frame = CGRect(x: 180, y: 6, width: 17, height: 17)
undoButton.isUserInteractionEnabled = true
undoButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(undoPressed)))
addSubview(forwardButton)
addSubview(rightButton)
addSubview(leftButton)
addSubview(undoButton)
}
@objc func forwardPressed() {
clearSelection()
selectButton(button: forwardButton)
delegate?.forwardPressed()
}
@objc func rightPressed() {
clearSelection()
selectButton(button: rightButton)
delegate?.rightPressed()
}
@objc func leftPressed() {
clearSelection()
selectButton(button: leftButton)
delegate?.leftPressed()
}
@objc func undoPressed() {
clearSelection()
selectButton(button: undoButton)
delegate?.undoPressed()
}
func clearSelection() {
clearSelection(button: forwardButton)
clearSelection(button: rightButton)
clearSelection(button: leftButton)
clearSelection(button: undoButton)
}
func selectButton(button: UIImageView) {
let shadowPath = UIBezierPath(rect: button.bounds)
button.layer.masksToBounds = false
button.layer.shadowColor = UIColor.yellow.cgColor
button.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
button.layer.shadowOpacity = 0.1
button.layer.shadowPath = shadowPath.cgPath
}
func clearSelection(button: UIImageView) {
button.layer.shadowOpacity = 0.0
}
}
|
//
// TravelyApp.swift
// Travely
//
// Created by alip on 19/06/21.
//
import SwiftUI
@main
struct TravelyApp: App {
@StateObject private var modelData = ModelData()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(modelData)
}
}
}
|
//
// EditButtons.swift
// SwitchSpeak-iOS
//
// Created by Robert Gerdisch on 4/11/18.
// Copyright © 2018 SwitchSpeak. All rights reserved.
//
import UIKit
class ButtonEditView: UIView {
var buttonNode:ButtonNode?
private var blurEffectView:UIVisualEffectView
private let framePadding:CGFloat = 10
private let uiGridSize:CGFloat = 3 // Note this has nothing to do with the switch grid. Just for internal visual spacing.
private var buttonSize:CGFloat
private var swapButton:UIButton?
var swapping:Bool = false {
didSet {
if swapping {
swapButton!.backgroundColor = UIColor.white
swapButton!.setTitleColor(UIColor.black, for: .normal)
} else {
swapButton!.backgroundColor = nil
swapButton!.setTitleColor(UIColor.white, for: .normal)
}
}
}
convenience init(buttonNode:ButtonNode, containerView:UIView) {
self.init(frame: buttonNode.button.frame)
self.buttonNode = buttonNode
if(buttonNode.cardData!.type == .category) {
let stepButton:UIButton = constructButton(withTitle: "Step", size: buttonSize)
stepButton.frame = CGRect(x: framePadding, y: frame.height - framePadding - buttonSize, width: buttonSize, height: buttonSize)
stepButton.tag = 2
blurEffectView.contentView.addSubview(stepButton)
}
containerView.addSubview(self)
containerView.bringSubview(toFront: self)
}
override init(frame:CGRect) {
blurEffectView = UIVisualEffectView()
swapping = false
let minFrameDim:CGFloat = (frame.width < frame.height) ? frame.width : frame.height
buttonSize = (minFrameDim - framePadding * 2) / uiGridSize
super.init(frame: frame)
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.layer.cornerRadius = 10 // To match ButtonNode
blurEffectView.clipsToBounds = true
let editButton:UIButton = constructButton(withTitle: "Edit", size: buttonSize)
editButton.frame = CGRect(x: framePadding, y: framePadding, width: buttonSize, height: buttonSize)
editButton.tag = 0
swapButton = constructButton(withTitle: "Swap", size: buttonSize)
swapButton!.frame = CGRect(x: frame.width - framePadding - buttonSize, y: framePadding, width: buttonSize, height: buttonSize)
swapButton!.tag = 1
blurEffectView.contentView.addSubview(editButton)
blurEffectView.contentView.addSubview(swapButton!)
self.addSubview(blurEffectView)
}
private func constructButton(withTitle title:String, size:CGFloat) -> UIButton {
let button:UIButton = UIButton(type: .custom)
button.setTitle(title, for: .normal)
button.layer.cornerRadius = 0.5 * size
button.clipsToBounds = true
button.layer.borderColor = UIColor.white.cgColor
button.layer.borderWidth = 2
button.addTarget(self, action: #selector(touchButton), for: .touchDown)
button.addTarget(self, action: #selector(tapButton), for: .touchUpInside)
return button
}
func fadeIn() {
UIView.animate(withDuration: 0.4, animations: {
self.blurEffectView.effect = UIBlurEffect(style: .dark)
})
}
func fadeOut() {
UIView.animate(withDuration: 0.15, animations: {
self.blurEffectView.effect = nil
}, completion: { (finished:Bool) in
if finished {
self.removeFromSuperview()
}
})
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
TouchSelectionUI.getTouchGrid().setButtonBeingEdited(nil)
}
@objc func touchButton(_ sender:UIButton) {
sender.alpha = 0.5;
}
@objc func tapButton(_ sender:UIButton) {
sender.alpha = 1.0;
switch sender.tag {
case 0: // Edit
let alert = UIAlertController(title: "Coming soon", message: "This feature is under construction!", preferredStyle: .alert)
TouchSelectionUI.getViewController().present(alert, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
alert.dismiss(animated: true, completion: nil)
}
break
case 1: // Swap
swapping = !swapping
break
case 2: // Step
TouchSelectionUI.getTouchSelection().setScreenId(buttonNode!.cardId)
break
default:
fatalError("Somehow a button was tapped with an incorrect tag.")
break
}
}
// Sticking this at the bottom since we need it but we don't use it.
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ModalAnimationController.swift
// Drinktionary
//
// Created by Kevin Weber on 3/27/15.
// Copyright (c) 2015 Distiinct Media, Inc. All rights reserved.
//
class ModalAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
var reverseAnimation: Bool!
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.2
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!.view
let toView = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!.view
let containerView = transitionContext.containerView()
if !reverseAnimation {
containerView?.addSubview(toView)
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
toView.alpha = 1.0
}, completion: { (Bool) -> Void in
transitionContext.completeTransition(true)
})
}
else {
containerView?.addSubview(fromView)
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
fromView.alpha = 0.0
}, completion: { (Bool) -> Void in
transitionContext.completeTransition(true)
})
}
}
} |
//
// PageViewController.swift
// AppleStore
//
// Created by Ivan Haidukov on 11.01.2020.
// Copyright © 2020 Ivan Haidukov. All rights reserved.
//
import UIKit
class PageViewController: UIPageViewController {
let promoImageArray: [String] = ["promo1", "promo2", "promo3", "promo4", "promo5"]
lazy var promoVCArray: [PromoViewController] = {
var newArray = [PromoViewController]()
var newVC: PromoViewController
for item in promoImageArray {
if let image = UIImage(named: item) {
newVC = PromoViewController(image: image)
newArray.append(newVC)
}
}
return newArray
}()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
createNavBarImage()
}
func createNavBarImage() {
let nav = self.navigationController?.navigationBar
nav?.barStyle = UIBarStyle.black
let width: CGFloat = 40
let height: CGFloat = 40
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44))
let imageView = UIImageView(frame: CGRect(x: (view.bounds.width)/2 - width, y: (44 - height)/2, width: width, height: height))
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: "appleIcon")
titleView.addSubview(imageView)
navigationItem.titleView = titleView
}
override func awakeFromNib() {
super.awakeFromNib()
if !promoVCArray.isEmpty {
setViewControllers([promoVCArray[0]], direction: .forward, animated: true, completion: nil)
}
}
}
extension PageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewController = viewController as? PromoViewController else { return nil }
if let index = promoVCArray.index(of: viewController) {
if index > 0 {
return promoVCArray[index - 1]
} else {
return promoVCArray.last
}
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewController = viewController as? PromoViewController else { return nil }
if let index = promoVCArray.index(of: viewController) {
if index != promoVCArray.count - 1 {
return promoVCArray[index + 1]
} else {
return promoVCArray[0]
}
}
return nil
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return promoVCArray.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
|
//
// API+AllCallenges.swift
// ETBAROON
//
// Created by imac on 10/1/17.
// Copyright © 2017 IAS. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class API_AllCallenges: NSObject {
class func getAllChallenges(fldAppPlayerID:Int = 1 , completion: @escaping (_ error: Error?, _ getAllChallenges: [GetChallenge]?)->Void) {
let url = "http://ias-systems.com/IAS_SW/ETBAROON/core/AcceptAndRejectChallenge/apiGetAllChallenges.php"
let parameters: [String: Any] = [
"fldAppPlayerID":fldAppPlayerID
]
// Int(helper.getTeamId()!)!
Alamofire.request(url, method: .post, parameters:parameters, encoding: URLEncoding.default, headers: nil)
//.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result
{
case .failure(let error):
completion(error, nil)
print(error)
case .success(let value):
let json = JSON(value)
//let Modle = json["products"]["data"].array
//let Models = Modle["models"].
//print(Modle)
//let dataArr = json["products"].array!
//print(dataArr)
guard let dataArr = json["message"]["all_challenges"].array
else {
completion(nil, nil)
return
}
print(dataArr)
var tChallenges = [GetChallenge]()
for data in dataArr {
guard let data = data.dictionary else{return}
let tChallenge = GetChallenge()
tChallenge.fldAppGameID=data["fldAppGameID"]?.string ?? "غيرموجود"
// cat.Price=data["price"]?.string ?? ""
tChallenge.fldAppTeamID1 = data["fldAppTeamID1"]?.string ?? ""
tChallenge.fldAppGameDateTime = data["fldAppGameDateTime"]?.string ?? ""
tChallenge.fldAppPlaygroundName = data["fldAppPlaygroundName"]?.string ?? "غيرموجود"
tChallenge.fldAppTeamID2 = data["fldAppTeamID2"]?.string ?? "غيرموجود"
tChallenge.fldAppTeamName1 = data["fldAppTeamName1"]?.string ?? "غيرموجود"
tChallenge.fldAppTeamName2 = data["fldAppTeamName2"]?.string ?? "غيرموجود"
tChallenge.fldAppTeamName2 = data["fldAppTeamName2"]?.string ?? "غيرموجود"
//pla.Countery = data["countryTitle"]?.string ?? "غيرموجود"
tChallenges.append(tChallenge)
}
// let last_page = json["products"]["last_page"].int ?? page
completion(nil, tChallenges)
}
//completion(nil, tasks, last_page)
}
}
class func acceptChallenge(fldAppGameID : String, completion: @escaping (_ error: Error?, _ success: Bool)->Void){
let url = "http://ias-systems.com/IAS_SW/ETBAROON/core/AcceptAndRejectChallenge/apiAcceptChallenge.php"
let parameter = [
"fldAppGameID" : fldAppGameID
]
Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result
{
case .failure(let error):
completion(error, false)
print(error)
case .success(let value):
let json = JSON(value)
// if let userId = json["message"]["fldAppUserID"].string {
// print(userId)
// helper.saveApiToken(userId: userId)
completion(nil, true)
// print(value)
}
}
}
class func rejectChallenge(fldAppGameID : String, completion: @escaping (_ error: Error?, _ success: Bool)->Void){
let url = "http://ias-systems.com/IAS_SW/ETBAROON/core/AcceptAndRejectChallenge/apiRejectChallenge.php"
let parameter = [
"fldAppGameID" : fldAppGameID
]
Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result
{
case .failure(let error):
completion(error, false)
print(error)
case .success(let value):
let json = JSON(value)
// if let userId = json["message"]["fldAppUserID"].string {
// print(userId)
// helper.saveApiToken(userId: userId)
completion(nil, true)
// print(value)
}
}
}
}
|
//
// NSfetchRequestResult+Protocol.swift
// Moody
//
// Created by yingkelei on 2020/11/30.
//
import UIKit
import CoreData
protocol Managed: class, NSFetchRequestResult {
static var entityName: String {get}
static var defaultSortDescriptors: [NSSortDescriptor] {get}
}
extension Managed {
static var defaultSortDescriptors: [NSSortDescriptor] {
return []
}
static var sortedFetchRequest: NSFetchRequest<Self> {
let request = NSFetchRequest<Self>(entityName: entityName)
request.sortDescriptors = defaultSortDescriptors
return request
}
}
extension Managed where Self: NSManagedObject {
static var entityName: String {
guard let name = entity().name else {
fatalError("Entity name is nil: \(self.description())")
}
return name
}
}
|
//
// SaltsideImageExtension.swift
// SaltSideTechnologiesAssignment
//
// Created by Lakshmi Ranganatha Hema on 1/13/21.
//
import Foundation
import UIKit
//LRU cache with capacity 5 is initialised
let imageCache = SaltsideLRUCache<String, Any>(SaltsideConstants.saltsideLRUMaxCacheSize)
class CacheImageView : UIImageView{
//This is used to cross check with urlstring before loading into imageview, to avoid mismatch of images on scroll etc...
var imageUrlString = String()
func loadImageViewWithUrlString(urlString : String){
imageUrlString = urlString
let url = URL(string: urlString)
image = nil
//Check if the image with urlstring is present in cache, if present fetch from cache else, fetch image from urlString and save in lrucache
if imageCache.isValid(key: urlString){
self.image = imageCache.get(urlString) as? UIImage
return
}
URLSession.shared.dataTask(with: url!){(data, response, error) in
if error != nil{
print(error?.localizedDescription ?? "Error occured while fetching image from url")
return
}
if data == nil{
print("No data found")
return
}
guard let imageToCache = UIImage(data: data!) else{
print("Error occured while fetchimng image from url \(urlString)")
return
}
imageCache.put(urlString, imageToCache)
DispatchQueue.main.async {[weak self] in
if self?.imageUrlString == urlString{
self?.image = imageToCache
}
}
}.resume()
}
}
|
//
// UIImage+exts.swift
// one-note
//
// Created by zuber on 2018/9/10.
// Copyright © 2018年 duzhe. All rights reserved.
//
import UIKit
public extension UIImage{
//图像比例缩放
public func scaleImage(_ scaleSize:CGFloat)->UIImage{
UIGraphicsBeginImageContext(CGSize(width: self.size.width * scaleSize, height: self.size.height * scaleSize))
self.draw(in: CGRect(x: 0, y: 0, width: CGFloat( Int(self.size.width * scaleSize) + 1 ) , height: self.size.height * scaleSize + 1))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
//自定长宽 相当于裁剪分辨率
public func reSizeImage(_ toSize:CGSize)->UIImage{
UIGraphicsBeginImageContext(toSize)
self.draw(in: CGRect(x: 0, y: 0, width: toSize.width, height: toSize.height))
let reSizeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return reSizeImage!
}
/// 等比例裁剪分辨率
///
/// - Parameter width: 指定最大宽度
/// - Returns: UIImage
public func resizeWidthTo(_ width: CGFloat) -> UIImage {
if width >= size.width {
return self
}
let heght = size.height * (width/size.width)
print("裁剪分辨率后w,h:\(width),\(heght)")
let newSize = CGSize(width: width, height: heght)
return reSizeImage(newSize)
}
}
|
//===--- PRNG.swift -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
public func rand32() -> UInt32 {
return _swift_stdlib_cxx11_mt19937()
}
public func rand32(exclusiveUpperBound limit: UInt32) -> UInt32 {
return _swift_stdlib_cxx11_mt19937_uniform(limit)
}
public func rand64() -> UInt64 {
return
(UInt64(_swift_stdlib_cxx11_mt19937()) << 32) |
UInt64(_swift_stdlib_cxx11_mt19937())
}
public func randInt() -> Int {
#if arch(i386) || arch(arm)
return Int(Int32(bitPattern: rand32()))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
return Int(Int64(bitPattern: rand64()))
#else
fatalError("unimplemented")
#endif
}
public func randArray64(_ count: Int) -> [UInt64] {
var result = [UInt64](repeating: 0, count: count)
for i in result.indices {
result[i] = rand64()
}
return result
}
public func randArray(_ count: Int) -> [Int] {
var result = [Int](repeating: 0, count: count)
for i in result.indices {
result[i] = randInt()
}
return result
}
public func pickRandom<
C : RandomAccessCollection
>(_ c: C) -> C.Iterator.Element {
let i = Int(rand32(exclusiveUpperBound: numericCast(c.count)))
return c[c.index(c.startIndex, offsetBy: numericCast(i))]
}
|
//: Playground - noun: a place where people can play
// Obtained from:
//
// http://stackoverflow.com/questions/27327067/append-text-or-data-to-text-file-in-swift
//
// Minor modifications made by R. Gordon on 15-11-15.
import Cocoa
extension String {
func appendLineToURL(fileURL: NSURL) throws {
try self.stringByAppendingString("\n").appendToURL(fileURL)
}
func appendToURL(fileURL: NSURL) throws {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
try data.appendToURL(fileURL)
}
}
extension NSData {
func appendToURL(fileURL: NSURL) throws {
if let fileHandle = try? NSFileHandle(forWritingToURL: fileURL) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.writeData(self)
}
else {
try writeToURL(fileURL, options: .DataWritingAtomic)
}
}
}
// Get path to the Documents folder
let documentPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
// Append folder name of Shared Playground Data folder
let sharedDataPath = documentPath.stringByAppendingPathComponent("Shared Playground Data")
// Append file name to folder path string
let filePath = sharedDataPath + "/output.txt"
// Test
do {
let url = NSURL(fileURLWithPath: filePath)
try "Test \(NSDate())".appendLineToURL(url)
let result = try String(contentsOfURL: url)
}
catch {
print("Could not write to file")
}
// Test writing an "1" to file
do {
let url = NSURL(fileURLWithPath: filePath)
try "1".appendToURL(url)
let result = try String(contentsOfURL: url)
}
catch {
print("Could not write to file")
}
// Test writing a "2" to file
do {
let url = NSURL(fileURLWithPath: filePath)
try "2".appendToURL(url)
let result = try String(contentsOfURL: url)
}
catch {
print("Could not write to file")
}
// Test writing a "3 and new line" to file
do {
let url = NSURL(fileURLWithPath: filePath)
try "3".appendLineToURL(url)
let result = try String(contentsOfURL: url)
}
catch {
print("Could not write to file")
} |
//
// getinfoModel.swift
// huicheng
//
// Created by lvxin on 2018/4/20.
// Copyright © 2018年 lvxin. All rights reserved.
//
import UIKit
import ObjectMapper
class getinfoDealModel: Mappable {
var id: Int!
var dealsnum: String!
var begintime: String!
var endtime: String!
var amount: String!
var img: String!
var dealpaylasttime: String!
var ispaper: Int!
var ispaperStr : String!
var paper : String = ""
var creditcode : String = ""
var branch: String!
var state: Int!
var invoicetype :Int!
var invoicetypeStr :String!
var stateStr: String!
var admin: String!
var applytime: String!
var note: String!
var type: Int!
var typeStr: String!
var casenum: String!
var n : String!
var rt : String!
var pn: String!
var pc: String!
var pp: String!
var pz: String!
var pj: String!
var pd: String!
var pa: String!
var on: String!
var oc: String!
var op : String!
var oz : String!
var oj: String!
var oa: String!
var r: String!
var rStr: String!
var mn: String!
var mf: String!
var mu: String!
var d: Int!
var dStr: String!
var w1 : String!
var w1Str : String!
var w2: String!
var w2Str: String!
var ct : String!
var sj: String!
var addtime: String!
var mt: String!
init() {}
required init?(map: Map){
mapping(map: map)
}
// Mappable
func mapping(map: Map) {
id <- map["id"]
dealsnum <- map["dealsnum"]
mn <- map["mn"]
mf <- map["mf"]
invoicetype <- map["invoicetype"]
invoicetypeStr <- map["invoicetypeStr"]
creditcode <- map["creditcode"]
mu <- map["mu"]
begintime <- map["begintime"]
type <- map["type"]
endtime <- map["endtime"]
amount <- map["amount"]
dealpaylasttime <- map["dealpaylasttime"]
img <- map["img"]
ispaper <- map["ispaper"]
ispaperStr <- map["ispaperStr"]
paper <- map["paper"]
branch <- map["branch"]
state <- map["state"]
stateStr <- map["stateStr"]
admin <- map["admin"]
applytime <- map["applytime"]
note <- map["note"]
type <- map["type"]
typeStr <- map["typeStr"]
casenum <- map["casenum"]
n <- map["n"]
rt <- map["rt"]
pn <- map["pn"]
pc <- map["pc"]
pz <- map["pz"]
pj <- map["pj"]
pd <- map["pd"]
pa <- map["pa"]
pp <- map["pp"]
on <- map["on"]
oc <- map["oc"]
op <- map["op"]
oz <- map["oz"]
oj <- map["oj"]
oa <- map["oa"]
r <- map["r"]
rStr <- map["rStr"]
d <- map["d"]
dStr <- map["dStr"]
w1 <- map["w1"]
w1Str <- map["w1Str"]
w2 <- map["w2"]
w2Str <- map["w2Str"]
ct <- map["ct"]
sj <- map["sj"]
addtime <- map["addtime"]
mt <- map["mt"]
}
}
|
//
// MyTabBarController.swift
// MyLocations
//
// Created by Jeffery Trotz on 4/17/19.
// Copyright © 2019 Jeffery Trotz. All rights reserved.
//
import UIKit
class MyTabBarController: UITabBarController
{
// Change the status bar text color to white
override var preferredStatusBarStyle: UIStatusBarStyle
{
return .lightContent
}
// By returning nil, the tab bar controller will look at its own
// preferredStatusBarStyle property instead of those from the
// other view controllers
override var childForStatusBarStyle: UIViewController?
{
return nil
}
}
|
//
// NewsFeedPresenter.swift
// VKFeedApp
//
// Created by Egor Lass on 25.02.2021.
// Copyright (c) 2021 Egor Mezhin. All rights reserved.
//
import UIKit
protocol NewsFeedPresentationLogic {
func presentData(response: NewsFeed.Model.Response.ResponseType)
}
class NewsFeedPresenter: NewsFeedPresentationLogic {
weak var viewController: NewsFeedDisplayLogic?
var cellLayoutCalculator: NewsFeedCellLayoutCalculatorProtocol = NewsFeedCellLayoutCalculator()
var dateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "ru_RU")
dateFormatter.dateFormat = "d MMM 'в' HH:mm"
return dateFormatter
}
func presentData(response: NewsFeed.Model.Response.ResponseType) {
switch response {
case .presentNewsFeed(feed: let feed, let revealPostIds):
let cells = feed.items.map { (feedItem) in
cellViewModel(from: feedItem, profiles: feed.profiles, groups: feed.groups, revealPostIds: revealPostIds)
}
let footerTitle = String.localizedStringWithFormat(NSLocalizedString("newsfeed cell count", comment: ""), cells.count)
let feedViewModel = FeedViewModel.init(cells: cells, footerTitle: footerTitle)
viewController?.displayData(viewModel: NewsFeed.Model.ViewModel.ViewModelData.displayNewsFeed(feedViewModel: feedViewModel))
case .presentUserInfo(user: let user):
let userViewModel = UserViewModel.init(photoUrlString: user?.photo100)
viewController?.displayData(viewModel: NewsFeed.Model.ViewModel.ViewModelData.displatUser(userViewModel: userViewModel))
case .presentFooterLoader:
viewController?.displayData(viewModel: NewsFeed.Model.ViewModel.ViewModelData.displayFooterLoader)
}
}
private func cellViewModel(from feedItem: FeedItem, profiles: [Profile], groups: [Group], revealPostIds: [Int]) -> FeedViewModel.Cell {
let date = Date(timeIntervalSince1970: feedItem.date)
let dateTitle = dateFormatter.string(from: date)
let profile = self.profile(for: feedItem.sourceId, profiles: profiles, groups: groups)
let photoAttachments = self.photoAttachments(feedItem: feedItem)
let isFullSize = revealPostIds.contains(feedItem.postId)
let sizes = cellLayoutCalculator.sizes(postText: feedItem.text, photoAttachments: photoAttachments, isFullSizePost: isFullSize)
let postText = feedItem.text?.replacingOccurrences(of: "<br>", with: "\n")
return FeedViewModel.Cell.init(
postId: feedItem.postId,
iconURLString: profile.photo,
name: profile.name,
date: dateTitle,
text: postText,
likeNumber: formattedCounter(feedItem.likes?.count),
commentNumber: formattedCounter(feedItem.comments?.count),
shareNumber: formattedCounter(feedItem.reposts?.count),
viewNumber: formattedCounter(feedItem.views?.count),
photoAttachments: photoAttachments,
sizes: sizes)
}
private func formattedCounter(_ counter: Int?) -> String? {
guard let counter = counter else { return nil }
var counterString = String(counter)
if counterString.count <= 6 && counterString.count >= 4 {
counterString = String(counterString.dropLast(3)) + "K"
}
return counterString
}
private func profile(for sourceId: Int, profiles: [Profile], groups: [Group]) -> ProfileRepresentable {
let profilesAndGroups: [ProfileRepresentable] = sourceId >= 0 ? profiles : groups
let normalSourceId = sourceId >= 0 ? sourceId : -sourceId
let profileRepresentable = profilesAndGroups.first { (myProfileRepresentable) -> Bool in
myProfileRepresentable.id == normalSourceId
}
return profileRepresentable!
}
private func photoAttachment(feedItem: FeedItem) -> FeedViewModel.FeedCellPhotoAttachment? {
guard let photos = feedItem.attachments?.compactMap({ (attachment) in
attachment.photo
}), let firstPhoto = photos.first else {
return nil
}
return FeedViewModel.FeedCellPhotoAttachment.init(photoUrlString: firstPhoto.url, width: firstPhoto.width, height: firstPhoto.height)
}
private func photoAttachments(feedItem: FeedItem) -> [FeedViewModel.FeedCellPhotoAttachment] {
guard let attachments = feedItem.attachments else { return [] }
return attachments.compactMap { (attachment) -> FeedViewModel.FeedCellPhotoAttachment? in
guard let photo = attachment.photo else { return nil }
return FeedViewModel.FeedCellPhotoAttachment.init(photoUrlString: photo.url,
width: photo.width,
height: photo.height)
}
}
}
|
//
// List.swift
// ParisWeather
//
// Created by Xav Mac on 12/03/2020.
// Copyright © 2020 ParisWeather. All rights reserved.
//
import Foundation
// MARK: - List
struct List: Codable {
let dt: Int
let main: MainDetails
let weather: [Weather]
let clouds: Clouds
let wind: Wind
let sys: Sys
let dtTxt: String
let rain: Rain?
enum CodingKeys: String, CodingKey {
case dt, main, weather, clouds, wind, sys
case dtTxt = "dt_txt"
case rain
}
}
|
//
// ProtocolsNavController.swift
// szenzormodalitasok
//
// Created by Tóth Zoltán on 2021. 05. 09..
// Copyright © 2021. Tóth Zoltán. All rights reserved.
//
// Imports
import UIKit
// ProtocolsNavigationController class
class ProtocolsNavigationController : UINavigationController {
// viewDidLoad func
override func viewDidLoad() {
super.viewDidLoad()
}
// awakeFromNib func
override func awakeFromNib() {
super.awakeFromNib()
tabBarItem.title = NSLocalizedString("protocolsTab.title", comment: "")
}
}
|
//
// ViewController.swift
// map
//
// Created by user on 21.03.2021.
//
import UIKit
class WelcomeViewController: UIViewController {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var registerButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
registerButton.layer.cornerRadius = 25
loginButton.layer.cornerRadius = 25
loginButton.layer.borderWidth = 2
registerButton.layer.borderWidth = 2
loginButton.layer.borderColor = UIColor.systemIndigo.cgColor
registerButton.layer.borderColor = UIColor.systemIndigo.cgColor
}
}
|
import XCTest
XCTMain([testCase(PrimeTests.allTests)])
func getPrimes(from start: Int, to end: Int) -> [Int] {
var retVal: [Int] = []
if(start < end) {
for i in start...end {
if(i.isPrime()) {
retVal.append(i)
}
}
} else {
for i in end...start {
if(i.isPrime()) {
retVal.append(i)
}
}
}
return retVal
} |
//
// NewsCell.swift
// MyNews
//
// Created by Yaroslava HLIBOCHKO on 8/5/19.
// Copyright © 2019 Yaroslava HLIBOCHKO. All rights reserved.
//
import UIKit
class NewsCell: UITableViewCell {
let sourceNameLabel: UILabel = {
let source = UILabel()
source.numberOfLines = 0
source.textColor = .blue
source.font = UIFont.systemFont(ofSize: 16)
return source
}()
let descriptionLabel: UILabel = {
let description = UILabel()
description.numberOfLines = 0
description.textColor = .gray
description.font = UIFont.systemFont(ofSize: 20)
return description
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSourceLabel()
addDescriptionLabel()
}
private func addSourceLabel() {
addSubview(sourceNameLabel)
sourceNameLabel.translatesAutoresizingMaskIntoConstraints = false
sourceNameLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
sourceNameLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
sourceNameLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
}
private func addDescriptionLabel() {
addSubview(descriptionLabel)
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.topAnchor.constraint(equalTo: sourceNameLabel.topAnchor, constant: 25).isActive = true
descriptionLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
descriptionLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
// MIT License
//
// Copyright (c) 2017 Joni Van Roost
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
/// This delegate is used for delegating `VerticalCardSwiper` actions.
@objc public protocol VerticalCardSwiperDelegate: AnyObject {
/**
Called right before a CardCell animates off screen. At this point there's already no way back.
You'll want to delete your item from the datasource here.
- parameter card: The CardCell that is being swiped away.
- parameter index: The index of the card that is being removed.
- parameter swipeDirection: The direction the card is swiped in. This can be Left, Right or None.
*/
@objc optional func willSwipeCardAway(card: CardCell, index: Int, swipeDirection: SwipeDirection)
/**
Called when a CardCell has animated off screen.
- parameter card: The CardCell that is being swiped away.
- parameter index: The index of the card that is being removed.
- parameter swipeDirection: The direction the card is swiped in. This can be Left, Right or None.
*/
@objc optional func didSwipeCardAway(card: CardCell, index: Int, swipeDirection: SwipeDirection)
/**
Called when a swipe is aborted because the minimum threshold wasn't reached.
- parameter card: The CardCell that was swiped.
- parameter index: The index of the was swiped.
*/
@objc optional func didCancelSwipe(card: CardCell, index: Int)
/**
Called while the user is dragging a card to a side.
You can use this to add some custom features to a card when it enters a certain `swipeDirection` (like overlays).
- parameter card: The CardCell that the user is currently dragging.
- parameter index: The index of the CardCell that is currently being dragged.
- parameter swipeDirection: The direction in which the card is being dragged.
*/
@objc optional func didDragCard(card: CardCell, index: Int, swipeDirection: SwipeDirection)
/**
Tells the delegate when the user taps a card.
- parameter verticalCardSwiperView: The `VerticalCardSwiperView` that displays the cardcells.
- parameter index: The index of the CardCell that was tapped.
*/
@objc optional func didTapCard(verticalCardSwiperView: VerticalCardSwiperView, index: Int)
/**
Tells the delegate when the user holds a card.
- parameter verticalCardSwiperView: The `VerticalCardSwiperView` that displays the cardcells.
- parameter index: The index of the CardCell that was tapped.
- parameter state: The state of the long press gesture.
*/
@objc optional func didHoldCard(verticalCardSwiperView: VerticalCardSwiperView, index: Int, state: UITapGestureRecognizer.State)
/**
Tells the delegate when the user scrolls through the cards.
- parameter verticalCardSwiperView: The `VerticalCardSwiperView` that displays the cardcells.
*/
@objc optional func didScroll(verticalCardSwiperView: VerticalCardSwiperView)
/**
Tells the delegate when scrolling through the cards came to an end.
- parameter verticalCardSwiperView: The `VerticalCardSwiperView` that displays the cardcells.
*/
@objc optional func didEndScroll(verticalCardSwiperView: VerticalCardSwiperView)
/**
Allows you to return the size as a CGSize for each card at their specified index.
This function will be called for every card. You can customize each card to have a different size.
Because this function uses the standard `sizeForItem` function of a `UICollectionView` internally,
you should keep in mind that returning a very small cell size results in multiple columns (like a standard collectionview),
which is not supported at the moment and very buggy.
This function will also take the custom insets into account, in case (itemSize - insets) is negative,
it will not take the insets into account.
- parameter verticalCardSwiperView: The `VerticalCardSwiperView` that will display the `CardCell`.
- parameter index: The index for which we return the specific CGSize.
- returns: The size of each card for its respective index as a CGSize.
*/
@objc optional func sizeForItem(verticalCardSwiperView: VerticalCardSwiperView, index: Int) -> CGSize
}
|
//
// ViewController.swift
// jQuiz
//
// Created by Jay Strawn on 7/17/20.
// Copyright © 2020 Jay Strawn. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var soundButton: UIButton!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var clueLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var feedbackLabel: UILabel!
var clues: [Clue] = []
var correctAnswerClue: Clue?
var points: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
guard let imageUrl:URL = URL(string: logoImageURL) else { return }
logoImageView.load(url: imageUrl) // Cache locally
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.backgroundColor = .clear
getClues()
self.scoreLabel.text = "\(self.points)"
if SoundManager.shared.isSoundEnabled == false {
soundButton.setImage(UIImage(systemName: "speaker.slash"), for: .normal)
} else {
soundButton.setImage(UIImage(systemName: "speaker"), for: .normal)
}
SoundManager.shared.playSound()
}
//# MARK : - SetupUI
func setupUI() {
let randomInt = Int.random(in: 0...3)
correctAnswerClue = clues[randomInt]
let categoryLabelText = correctAnswerClue?.category.title ?? "Data Not Availbale"
setTextWithAnimation(with: categoryLabelText)
clueLabel.text = correctAnswerClue?.question
scoreLabel.text = points.description
tableView.reloadData()
}
func setTextWithAnimation(with text: String){
UIView.transition(
with: categoryLabel,
duration: 1,
options: .transitionFlipFromTop,
animations: { [weak self] in
self?.categoryLabel.text = "\(text)"
}, completion: nil
)
}
func showFeedback(with clue: Clue) {
guard let correctClue = correctAnswerClue else { return }
if clue.answer == correctClue.answer {
feedbackLabel.text = "Correct Answer! Score updated!"
points += correctClue.value ?? 1
} else {
feedbackLabel.text = "Wrong Answer! The correct answer was \(correctClue.answer). Try Again!"
}
//Next Question
self.getClues()
}
//# MARK : - Networking
func getClues() {
Networking.sharedInstance.getRandomCategory(completion: { (response, error) in
guard let clue = response else {
return
}
Networking.sharedInstance.getClues(clue: clue) { (response, error) in
self.clues = response
self.setupUI()
}
})
}
//# MARK : - Volume Setting
@IBAction func didPressVolumeButton(_ sender: Any) {
SoundManager.shared.toggleSoundPreference()
if SoundManager.shared.isSoundEnabled == false {
soundButton.setImage(UIImage(systemName: "speaker.slash"), for: .normal)
} else {
soundButton.setImage(UIImage(systemName: "speaker"), for: .normal)
}
}
}
//# MARK : - UITableView
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return clues.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
// cell.backgroundColor = .systemGray
cell.textLabel?.text = clues[indexPath.row].answer.html2String
cell.textLabel?.textAlignment = .center
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let option = clues[indexPath.row]
showFeedback(with:option )
}
}
extension URL {
init(staticString string: StaticString) {
guard let url = URL(string: "\(string)") else {
preconditionFailure("Invalid static URL string: \(string)")
}
self = url
}
}
//# MARK : Handle HTML Tags
extension Data {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var html2String: String { html2AttributedString?.string ?? "" }
}
extension StringProtocol {
var html2AttributedString: NSAttributedString? {
Data(utf8).html2AttributedString
}
var html2String: String {
html2AttributedString?.string ?? ""
}
}
|
// SocketsTests.swift
// Simplenet Socket module
// Copyright (c) 2018 Vladimir Raisov. All rights reserved.
// Licensed under MIT License
import XCTest
@testable import Sockets
@testable import Interfaces
class SocketTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBind() {
Interfaces().flatMap{$0.addresses}.forEach {
do {
let sock = try Socket(family: SocketAddressFamily(type(of: $0).family), type: .datagram, protocol: .udp)
let address = $0.with(port: 0x1122)
try sock.bind(address)
XCTAssertNotNil(sock.localAddress)
if let ip = sock.localAddress?.ip {
if let ip4 = ip as? in_addr {
XCTAssertEqual(ip4, $0 as! in_addr)
}
if var ip6 = ip as? in6_addr {
let iip6 = ip as! in6_addr
ip6.__u6_addr.__u6_addr16.1 = iip6.__u6_addr.__u6_addr16.1
XCTAssertEqual(ip6, ip as! in6_addr)
}
}
} catch {
XCTFail("\(error)")
}
}
}
func testBroadcastConnect() {
Interfaces().filter{$0.broadcast != nil}.forEach {
let brd = sockaddr_in($0.broadcast!, port: 0x1122)
do {
let sock = try Socket(family: .inet, type: .datagram, protocol: .udp)
try sock.enable(option: SO_BROADCAST, level: SOL_SOCKET)
XCTAssertTrue(try sock.enabled(option: SO_BROADCAST, level: SOL_SOCKET))
try sock.set(option: IP_BOUND_IF, level: IPPROTO_IP, value: $0.index)
XCTAssertEqual(try sock.get(option: IP_BOUND_IF, level: IPPROTO_IP), $0.index)
try sock.connectTo(brd)
XCTAssertNotNil(sock.remoteAddress)
if let ina = sock.remoteAddress as? sockaddr_in {
XCTAssertEqual(ina.sin_addr, brd.sin_addr)
XCTAssertEqual(ina.sin_port, brd.sin_port)
}
XCTAssertNotNil(sock.localAddress)
if let ina = sock.localAddress as? sockaddr_in {
XCTAssertNotNil($0.ip4.first{$0 == ina.sin_addr})
}
} catch {
XCTFail("\(error)")
}
}
}
func testConnect4() {
Interfaces().flatMap{$0.ip4}.forEach {
do {
let sock = try Socket(family: .inet, type: .datagram, protocol: .udp)
let sin = sockaddr_in($0, port:0x1122)
try sock.connectTo(sin)
XCTAssertNotNil(sock.remoteAddress)
if let ina = sock.remoteAddress as? sockaddr_in {
XCTAssertEqual(ina.sin_addr, sin.sin_addr)
XCTAssertEqual(ina.sin_port, sin.sin_port)
}
XCTAssertNotNil(sock.localAddress)
if let ina = sock.localAddress as? sockaddr_in {
XCTAssertEqual(ina.sin_addr, sin.sin_addr)
}
} catch {
XCTFail("\(error)")
}
}
}
func testConnect6() {
Interfaces().flatMap{$0.ip6}.forEach {
do {
let sock = try Socket(family: .inet6, type: .datagram, protocol: .udp)
let sin6 = sockaddr_in6($0, port:0x1122)
try sock.connectTo(sin6)
XCTAssertNotNil(sock.remoteAddress)
if var ina = sock.remoteAddress as? sockaddr_in6 {
ina.sin6_addr.__u6_addr.__u6_addr16.1 = sin6.sin6_addr.__u6_addr.__u6_addr16.1
XCTAssertEqual(ina.sin6_addr, sin6.sin6_addr)
XCTAssertEqual(ina.sin6_port, sin6.sin6_port)
}
XCTAssertNotNil(sock.localAddress)
if var ina = sock.localAddress as? sockaddr_in6 {
ina.sin6_addr.__u6_addr.__u6_addr16.1 = sin6.sin6_addr.__u6_addr.__u6_addr16.1
XCTAssertEqual(ina.sin6_addr, sin6.sin6_addr)
}
} catch {
XCTFail("\(error)")
}
}
}
func testBooleanOptions() {
do {
let sock = try Socket(family: .inet, type: .datagram, protocol: .udp)
let tested = [
(SO_BROADCAST, SOL_SOCKET),
(SO_REUSEADDR, SOL_SOCKET),
(SO_REUSEPORT, SOL_SOCKET),
(IP_RECVPKTINFO, IPPROTO_IP),
(IP_RECVDSTADDR, IPPROTO_IP),
(IP_RECVIF, IPPROTO_IP),
(IP_RECVTTL, IPPROTO_IP)]
for option in tested {
let currentStatus = try sock.enabled(option: option.0, level: option.1)
if currentStatus {
try sock.disable(option: option.0, level: option.1)
XCTAssertFalse(try sock.enabled(option: option.0, level: option.1))
try sock.enable(option: option.0, level: option.1)
XCTAssertTrue(try sock.enabled(option: option.0, level: option.1))
} else {
try sock.enable(option: option.0, level: option.1)
XCTAssertTrue(try sock.enabled(option: option.0, level: option.1))
try sock.disable(option: option.0, level: option.1)
XCTAssertFalse(try sock.enabled(option: option.0, level: option.1))
}
}
} catch {
XCTFail("\(error)")
}
}
func testBooleanOptions6() {
do {
let sock = try Socket(family: .inet6, type: .datagram, protocol: .udp)
let tested = [
(IPV6_V6ONLY, IPPROTO_IPV6),
(IPV6_BINDV6ONLY, IPPROTO_IPV6),
(IPV6_2292PKTINFO, IPPROTO_IPV6)]
for option in tested {
let currentStatus = try sock.enabled(option: option.0, level: option.1)
if currentStatus {
try sock.disable(option: option.0, level: option.1)
XCTAssertFalse(try sock.enabled(option: option.0, level: option.1))
try sock.enable(option: option.0, level: option.1)
XCTAssertTrue(try sock.enabled(option: option.0, level: option.1))
} else {
try sock.enable(option: option.0, level: option.1)
XCTAssertTrue(try sock.enabled(option: option.0, level: option.1))
try sock.disable(option: option.0, level: option.1)
XCTAssertFalse(try sock.enabled(option: option.0, level: option.1))
}
}
} catch {
XCTFail("\(error)")
}
}
}
|
//
// CustomizedView.swift
// InAppNotificationDemo
//
// Created by Arnold Plakolli on 5/16/18.
// Copyright © 2018 Arnold Plakolli. All rights reserved.
//
import UIKit
class CustomizedView: UIView {
var cornerRadius: CGFloat = 0.0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}
var borderWidth: CGFloat = 0.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
var borderColor: UIColor = UIColor.clear {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
func removeGestureRecgonizers() {
guard let _gestureReognizers = gestureRecognizers else { return }
for gestureRecognizer in _gestureReognizers {
removeGestureRecognizer(gestureRecognizer)
}
}
}
|
import UIKit
import FirebaseDatabase
import FirebaseStorage
import FirebaseAuth
import Firebase
class MyPageViewController: UIViewController {
@IBAction func logOut(_ sender: Any) {
try! Auth.auth().signOut()
self.performSegue(withIdentifier: "logOut", sender: self)
}
var authService = AuthService()
var user: User!
var dataBaseRef: DatabaseReference!{
return Database.database().reference()
}
var storageRef: StorageReference!{
return Storage.storage().reference()
}
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var avatar: UIImageView!
var phone = Int()
override func viewDidLoad() {
loadUserInfo()
print(phone)
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
// locationRef = Global.refString
print(phone)
// loadUserInfo()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// var locationRef = Global.refString
func loadUserInfo(){
let locationRef = Global.refString
let userRef = dataBaseRef.child(locationRef).child(Auth.auth().currentUser!.uid)
// let userRef = dataBaseRef.child("Users/\(Auth.auth().currentUser!.uid)")
userRef.observe(.value, with: { (snapshot) in
let user = Users(snapshot: snapshot)
if let username = user.name{
self.nameLabel.text = username
}
//
// if let pass = user.password{
// self.passwordOld = pass
// }
if let number = user.phoneNumber{
self.phone = Int(number)
}
if let userLocation = user.location{
self.bioLabel.text = userLocation
}
// if let bio = user.biography{
// self.biog.text = bio
// self.bioOld = bio
// }
// if let interests = user.interests{
// self.interests.text = interests
// self.interestsOld = interests
// }
if let imageOld = user.photoURL{
// let imageURL = user.photoURL!
self.storageRef.storage.reference(forURL: imageOld).getData(maxSize: 10 * 1024 * 1024, completion: { (imgData, error) in
if error == nil {
DispatchQueue.main.async {
if let data = imgData {
self.avatar.image = UIImage(data: data)
}
}
}else {
print(error!.localizedDescription)
}
}
)}
}) { (error) in
print(error.localizedDescription)
}
}
}
|
//
// ViewController.swift
// AnimeInformationS
//
// Created by Gerardo Herrera on 7/25/17.
// Copyright © 2017 Gerardo Herrera. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var colectionViewAnime: UICollectionView!
var arrayAnimes = [Anime]()
override func viewDidLoad() {
super.viewDidLoad()
initzializeData()
configureCollectionView()
//Do any additional setup after loading the view, typically from a nib.
}
//MARK:- Configure colectionViewAnime
func configureCollectionView()
{
colectionViewAnime.delegate = self
colectionViewAnime.dataSource = self
}
// MARK:- This Method can initzializeData (call methods API)
func initzializeData()
{
WebServiceAPI.getToken(completionHandler: { (band, message) in
print(message)
if band == true
{
WebServiceAPI.getListAnime(completionHandler: { (band, arrayAnime) in
print(band)
if ( band == true)
{
self.arrayAnimes = arrayAnime
DispatchQueue.main.async {
self.colectionViewAnime.reloadData()
}
}
})
}
})
}
func configurePopUp(sender: UITapGestureRecognizer)
{
var indexbyTag = 0
let storyBoard = UIStoryboard(name: "PreviewImage", bundle: nil)
let viewcontroller = storyBoard.instantiateViewController(withIdentifier: "preview") as! PreviewImageViewController
viewcontroller.image = (sender.view as! UIImageView).image!
indexbyTag = (sender.view?.tag)!
viewcontroller.tittleJapanese = self.arrayAnimes[indexbyTag].title_japanese
viewcontroller.tittleEnglish = self.arrayAnimes[indexbyTag].title_english
viewcontroller.type = self.arrayAnimes[indexbyTag].type
viewcontroller.popularity = "\(self.arrayAnimes[indexbyTag].popularity)"
viewcontroller.totalEpisodies = "\(self.arrayAnimes[indexbyTag].total_episodes)"
viewcontroller.score = "\(self.arrayAnimes[indexbyTag].average_score)"
viewcontroller.id = self.arrayAnimes[indexbyTag].id
viewcontroller.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
self.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
self.present(viewcontroller, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrayAnimes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : ItemAnimeCollectionViewCell = colectionViewAnime.dequeueReusableCell(withReuseIdentifier: "cellAnime", for: indexPath) as! ItemAnimeCollectionViewCell
cell.tittleLable.text = self.arrayAnimes[indexPath.row].title_english
cell.imageAnimeUIImage.loadImage(urlString: self.arrayAnimes[indexPath.row].image_url_lge)
cell.imageAnimeUIImage.isUserInteractionEnabled = true
cell.imageAnimeUIImage.tag = indexPath.row
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.configurePopUp(sender:)))
cell.imageAnimeUIImage.addGestureRecognizer(tapGesture)
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath.row)
}
}
|
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
import JYViewBuilder
class MyViewController : UIViewController {
override func loadView() {
self.view = VStack(spacing: 8){
label("hello")
label("word!")
for i in 0...5{
label("\(i)")
}
HStack{
label("hello")
label("word!")
}
if false {
label("hello true")
label("true word!")
} else {
label("hello false")
label("false word!")
label("false")
}
}
.distribution(.fillEqually)
}
private func label(_ text: String) -> UILabel {
let lb = UILabel()
lb.text = text
lb.backgroundColor = .lightGray
return lb
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
|
//
// WDEventsDataSource.swift
// WorldDevEvent
//
// Created by Bogdan Sasko on 5/29/19.
// Copyright © 2019 vinso. All rights reserved.
//
import UIKit
protocol WDEventsDataSourceProtocol: UITableViewDataSource {
func event(by indexPath: IndexPath) -> WDEvent
}
class WDEventsDataSource: NSObject {
var events: [WDEvent] = [
WDEvent(id: 1, type: .event, title: "Madison Sqaure Garden 2", shortDescription: "11.2.2019", description: "11.2.2019", smallImageURL: "http://mama-studio.com/tt/event1.png", bigImageURL: "http://mama-studio.com/tt/event11.png", latitude: 40.817817, longtitude: 74.251631),
WDEvent(id: 2, type: .event, title: "Early Winter SHOW", shortDescription: "11.2.2019", description: "21.3.2019", smallImageURL: "http://mama-studio.com/tt/event2.png", bigImageURL: "http://mama-studio.com/tt/event12.png", latitude: 40.817817, longtitude: 74.251631),
WDEvent(id: 3, type: .event, title: "Christmas DroidConf", shortDescription: "11.2.2019", description: "31.3.2019", smallImageURL: "http://mama-studio.com/tt/event3.png", bigImageURL: "http://mama-studio.com/tt/event13.png", latitude: 40.817817, longtitude: 74.251631)
]
private let kListEventCell = "ListEventCell"
}
extension WDEventsDataSource: WDEventsDataSourceProtocol {
func event(by indexPath: IndexPath) -> WDEvent {
return events[indexPath.row]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: kListEventCell) else {
print(#function, "can't find ListEventsCell in the object pool")
return UITableViewCell()
}
return cell
}
}
|
//
// LocationCell.swift
// MyLoqta
//
// Created by Ashish Chauhan on 26/07/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
class LocationCell: BaseTableViewCell, NibLoadableView, ReusableView {
@IBOutlet weak var lblPlaceHolder: UILabel!
@IBOutlet weak var imgViewCheck: UIImageView!
@IBOutlet weak var lblDetail: UILabel!
var textCount = 0 {
didSet {
if self.textCount > 0 {
self.imgViewCheck.isHidden = false
self.lblPlaceHolder.isHidden = false
} else {
self.imgViewCheck.isHidden = true
self.lblPlaceHolder.isHidden = true
}
}
}
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 configureCell(data: [String: Any]) {
if let placheHolder = data[Constant.keys.kTitle] as? String {
self.lblDetail.text = placheHolder
self.lblDetail.textColor = UIColor.colorWithAlpha(color: 166, alfa: 0.8)
}
if let value = data[Constant.keys.kValue] as? String, !value.isEmpty {
self.lblDetail.text = value
self.lblDetail.textColor = UIColor.colorWithAlpha(color: 116, alfa: 1.0)
textCount = value.utf8.count
}
}
}
|
import Foundation
import Dispatch
let applicationDocumentsDirectory: URL = {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}()
|
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// flutter channel
// static const _rotationChannel = const MethodChannel('com.op.tymobile/orientation');
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let rotationChannel = FlutterMethodChannel(
name: "com.op.tymobile/orientation",
binaryMessenger: controller.binaryMessenger)
// flutter call (call SystemChrome.setPreferredOrientation before invoke)
// _rotationChannel.invokeMethod('setLandscapeLeft');
// _rotationChannel.invokeMethod('setLandscapeRight');
// _rotationChannel.invokeMethod('setPortrait');
rotationChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: FlutterResult) -> Void in
// Note: this method is invoked on the UI thread.
guard call.method.hasPrefix("set") == true else {
print("error method name")
return
}
if "setLandscapeRight" == call.method {
UIDevice.current.setValue(NSNumber(value: UIInterfaceOrientation.landscapeRight.rawValue), forKey: "orientation")
} else if "setLandscapeLeft" == call.method {
UIDevice.current.setValue(NSNumber(value: UIInterfaceOrientation.landscapeLeft.rawValue), forKey: "orientation")
} else if "setPortrait" == call.method {
UIDevice.current.setValue(NSNumber(value: UIInterfaceOrientation.portrait.rawValue), forKey: "orientation")
} else {
result(FlutterMethodNotImplemented)
}
})
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
|
//
// WebVC.swift
// secondFeedrReader
//
// Created by David A. Schrijn on 3/23/17.
// Copyright © 2017 David A. Schrijn. All rights reserved.
//
import UIKit
import WebKit
class WebVC: UIViewController, WKUIDelegate {
// MARK: - IBOutlets
@IBOutlet weak var webView: UIWebView! // Deprecated!
@IBOutlet weak var webViewContainer: UIView!
// MARK: - Variables
var articlesInfo: FeedrInfo!
var wkWebView: WKWebView!
// MARK: - App Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureWKView()
if let url = URL(string:articlesInfo.pageUrl) {
let request = NSURLRequest(url: url)
wkWebView.load(request as URLRequest)
}
}
// MARK: - Functions
func configureWKView() {
let webConfiguration = WKWebViewConfiguration()
let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: webViewContainer.frame.size.height))
wkWebView = WKWebView(frame: customFrame, configuration: webConfiguration)
wkWebView.translatesAutoresizingMaskIntoConstraints = false
webViewContainer.addSubview(wkWebView)
wkWebView.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true
wkWebView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true
wkWebView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor).isActive = true
wkWebView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor).isActive = true
wkWebView.heightAnchor.constraint(equalTo: webViewContainer.heightAnchor).isActive = true
wkWebView.uiDelegate = self
}
// MARK: - IBActions
@IBAction func backBtn(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func newsAPIBtn(_ sender: Any) {
if let url = NSURL(string: "https://newsapi.org/") {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
}
}
}
|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import Combine
typealias ClipCollectionNavigationBarDependency = HasClipCollectionNavigationBarDelegate
enum ClipCollectionNavigationBarReducer: Reducer {
typealias Dependency = ClipCollectionNavigationBarDependency
typealias State = ClipCollectionNavigationBarState
typealias Action = ClipCollectionNavigationBarAction
static func execute(action: Action, state: State, dependency: Dependency) -> (State, [Effect<Action>]?) {
var nextState = state
let stream = Deferred {
Future<Action?, Never> { promise in
if let event = action.mapToEvent() {
dependency.clipCollectionNavigationBarDelegate?.didTriggered(event)
}
promise(.success(nil))
}
}
let eventEffect = Effect(stream)
switch action {
// MARK: - View Life-Cycle
case .viewDidLoad:
return (state.updatingAppearance(), [eventEffect])
// MARK: - State Observation
case let .stateChanged(clipCount: clipCount,
selectionCount: selectionCount,
operation: operation):
nextState.clipCount = clipCount
nextState.selectionCount = selectionCount
nextState.operation = operation
nextState = nextState.updatingAppearance()
return (nextState, [eventEffect])
// MARK: - NavigationBar
case .didTapCancel,
.didTapSelectAll,
.didTapDeselectAll,
.didTapSelect,
.didTapReorder,
.didTapDone:
return (state, [eventEffect])
}
}
}
private extension ClipCollectionNavigationBarState {
func updatingAppearance() -> Self {
var nextState = self
let isSelectedAll = clipCount <= selectionCount
let isSelectable = clipCount > 0
let existsClip = clipCount > 1
let rightItems: [Item]
let leftItems: [Item]
switch operation {
case .none:
rightItems = [
source.isAlbum ? .init(kind: .reorder, isEnabled: existsClip) : nil,
.init(kind: .select, isEnabled: isSelectable)
].compactMap { $0 }
leftItems = []
case .selecting:
rightItems = [.init(kind: .cancel, isEnabled: true)]
leftItems = [
isSelectedAll
? .init(kind: .deselectAll, isEnabled: true)
: .init(kind: .selectAll, isEnabled: true)
]
case .reordering:
rightItems = [.init(kind: .done, isEnabled: true)]
leftItems = []
}
nextState.rightItems = rightItems
nextState.leftItems = leftItems
return nextState
}
}
private extension ClipCollectionNavigationBarAction {
func mapToEvent() -> ClipCollectionNavigationBarEvent? {
switch self {
case .didTapCancel:
return .cancel
case .didTapSelectAll:
return .selectAll
case .didTapDeselectAll:
return .deselectAll
case .didTapSelect:
return .select
case .didTapReorder:
return .reorder
case .didTapDone:
return .done
default:
return nil
}
}
}
|
//
// AppDelegate.swift
// Emoji Dictionary
//
// Created by William Lund on 5/17/18.
// Copyright © 2018 Bill Lund. All rights reserved.
//
/*
Instructions
0. This app replaces the standard ViewController with a TableViewController.
0.0 First task is in the Storyboard to find the TableViewController and move it to the
storyboard. At this point you now have two ViewControllers.
0.1 The standard ViewController has an arrow pointing at it, which means it will be the entry
point screen and code. Move the arrow from the standard ViewController to the new
TableViewController. Alternately select the TableViewController, select Attributes Inspector
and click on "Is Initial ViewController".
0.2 Since we're not going to use the standard ViewController, delete it by deleting it from
the Storyboard hierarchy.
0.3 At this point Nick ran the code just to see the empty TableViewController and make sure
everything was working.
1. Get the TableViewController.swift code and link it to the TableViewController in the Storyboard
1.0 Delete the "ViewController.swift". Be sure to move to trash.
1.1 Add a new file.
1.1.0 Select Cocoa Touch Class.
1.1.1 Select SubClass of "UITableViewController"
1.1.2 Class name is "EmojiTableViewController"
1.1.3 May need to move it into the "Emoji Dictionary" folder.
1.2 There's a lot of stuff to be deleted.
1.2.1 Get rid of everything except
1.2.1.0 override func viewDidLoad()
1.2.1.1 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
1.2.1.2 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
Note that this one needs to be uncommented to become active.
1.3 In the Storyboard select the TableViewController, open the "Identity Inspector" and type in the name
of the class "EmojiTableViewController.swift". Now the visual is tied to the code.
1.4 In the hierarchy of the Storyboard, select "Table View Cell" under "Table View" and click on
"Attributes Inspector". Under "Identifier" type in a name, such as "myCell".
1.5 In following code of EmojiTableViewController.swift, enter "myCell" in...
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
2. Populate the TableView
2.0 In EmojiTableViewController.swift...
2.0.0 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20 // change from 0
}
2.0.1 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = "Hello World" // Add this line.
return cell
}
2.1 Create a class data element var emoji = [ "😄", <more emojis]. You can get the Emoji menu with
<cntl><command><space>.
2.2 Change tableView to return emoji.count
2.3 Change cell.textLabel?.text = emoji[indexPath.row]
2.4 This is now populating the table with the emojis from the array.
3. Create another ViewController to show the emoji and its name.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
//
// CreateAccountView.swift
// IvyHacks
//
// Created by Garima Bothra on 02/10/20.
//
import SwiftUI
import Firebase
struct CreateAccountView: View {
@State var email: String = ""
@State var password: String = ""
var body: some View {
GeometryReader { geometry in
ZStack
{
Color.primaryColor
.ignoresSafeArea()
VStack {
Text("Create Account")
.font(.largeTitle)
.bold()
Text("Welcome, Create a new profile to continue!")
.foregroundColor(.gray)
.font(.system(size: 14))
Spacer()
.frame(height: geometry.size.height/6)
TextField("Email", text: $email)
.padding([.leading, .trailing])
Rectangle()
.frame(height: 1.0 ,alignment: .bottom)
.foregroundColor(Color.gray)
.padding([.leading, .trailing])
TextField("Password", text: $password)
.padding([.leading, .trailing])
Rectangle()
.frame(height: 1.0 ,alignment: .bottom)
.foregroundColor(Color.gray)
.padding([.leading, .trailing])
Spacer()
.frame(height: geometry.size.height/6)
NavigationLink(destination: AccountDetailsView()) {
Button(action: {
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
// ...
}
}) {
Text("NEXT")
.bold()
.frame(width: geometry.size.width/2, height: 30)
.cornerRadius(10)
.foregroundColor(.white)
.background(Color.secondaryColor)
.cornerRadius(10)
}
}
}
}
}
}
}
struct CreateAccountView_Previews: PreviewProvider {
static var previews: some View {
CreateAccountView()
}
}
|
//
// PetTests.swift
// PetPickerTests
//
// Created by Steven Schwedt on 12/29/18.
// Copyright © 2018 Steven Schwedt. All rights reserved.
//
import XCTest
@testable import PetPicker
class PetTests: XCTestCase {
func testInitNewPet() {
let data = ["id": 3, "name": "Bingo", "species": "dog", "description": "Bark Bark", "pic": "http://www.google.com/dogpic", "user_id": 7] as [String: Any]
let pet = Pet(data: data)
XCTAssert(pet.id == 3)
XCTAssert(pet.name == "Bingo")
XCTAssert(pet.species == "dog")
XCTAssert(pet.user_id == 7)
}
}
|
//
// LabeledUIButton.swift
// SocialApp
//
// Created by Дима Давыдов on 30.12.2020.
//
import UIKit
protocol LabeledUIButtonDelegate: class {
func onButtonClick()
}
@IBDesignable
class LabeledUIButton: UIControl {
@IBOutlet weak var view: UIButton!
@IBInspectable var buttonImage: UIImage? {
get {
return view?.image(for: .normal)
}
set {
view.setImage(newValue, for: .normal)
}
}
@IBInspectable var buttonTextColor: UIColor? {
get {
return view.titleColor(for: .normal)
}
set {
view.setTitleColor(newValue, for: .normal)
}
}
weak var delegate: LabeledUIButtonDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
view = loadViewFromNib() as! UIButton?
view.frame = bounds
view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIButton
return view
}
}
|
//
// CGPhotoLibrarySettingConfig.swift
// CGPhoto
//
// Created by DY on 2017/11/30.
// Copyright © 2017年 DY. All rights reserved.
//
import UIKit
/// CGPhoto 相关视图的配置
class CGPhotoLibrarySettingConfig: NSObject {
static let defalutConfig = CGPhotoLibrarySettingConfig.init()
var photoCollectionConfig : CGPhotoCollectionViewConfig?
}
|
//
// TCPsocket.swift
// SnapE
//
// Created by WangXin on 3/24/16.
// Copyright © 2016 WangXin. All rights reserved.
//
import Foundation
class TCPRequest {
func connect(username: String, sessionId: String, token: String) {
/*
Connect Function
*/
// Connect Request builder and body
let connectRequestBuilder = ConnectRequest.Builder()
let connectRequest: ConnectRequest?
// Message Base builder and body
let msgBuilder = Msg.Builder()
var msg:Msg?
// connectresponse
do {
// Initialize connectRequest
connectRequestBuilder.setUsername(username).setToken(token).setSessionId(sessionId)
connectRequest = try connectRequestBuilder.build()
//Initialize meassage
msgBuilder.setBody(connectRequest!.data()).setMsgtype(Msg.Types.Connect)
msg = try msgBuilder.build()
let (success, errmsg) = tcpsocket.send(data: encoder(msg!))
if success {
print("Send Successfully!")
} else {
print("Connect Error: \(errmsg)")
}
} catch let e as NSError {
print(e.localizedDescription)
}
}
func contactUpdate(username: String) {
// Search Contact Request builder and body
let contactUpdateRequestBuilder = ContactUpdateRequest.Builder()
let contactUpdateRequest: ContactUpdateRequest?
// Message Base builder and body
let msgBuilder = Msg.Builder()
var msg:Msg?
do {
// Initialize searchContactRequest
contactUpdateRequestBuilder.setUsername(username)
contactUpdateRequest = try contactUpdateRequestBuilder.build()
//Initialize meassage
msgBuilder.setBody(contactUpdateRequest!.data()).setMsgtype(Msg.Types.ContactUpdate)
msg = try msgBuilder.build()
let (success, errmsg) = tcpsocket.send(data: encoder(msg!))
if success {
print("Send successfully!")
} else {
print("Connect Error: \(errmsg)")
}
} catch let e as NSError {
print(e.localizedDescription)
}
}
func searchContact(pageNum:Int32, keyword: String) {
/*
Search Contact Function
*/
// Search Contact Request builder and body
let searchContactRequestBuilder = SearchContactRequest.Builder()
let searchContactRequest: SearchContactRequest?
// Message Base builder and body
let msgBuilder = Msg.Builder()
var msg:Msg?
do {
// Initialize searchContactRequest
searchContactRequestBuilder.setKeyword(keyword).setPageNum(pageNum)
searchContactRequest = try searchContactRequestBuilder.build()
//Initialize meassage
msgBuilder.setBody(searchContactRequest!.data()).setMsgtype(Msg.Types.SearchContact)
msg = try msgBuilder.build()
let (success, errmsg) = tcpsocket.send(data: encoder(msg!))
if success {
print("Send successfully!")
} else {
print("Connect Error: \(errmsg)")
}
} catch let e as NSError {
print(e.localizedDescription)
}
}
func login(username: String, password: String) {
/*
Login Function
*/
// Login Request builder and body
let loginRequestBuilder = LoginRequest.Builder()
let loginRequest: LoginRequest?
// Message Base builder and body
let msgBuilder = Msg.Builder()
var msg: Msg?
do {
// Initialize loginRequest
loginRequestBuilder.setUsername(username).setPassword(password)
loginRequest = try loginRequestBuilder.build()
// Initialize message
msgBuilder.setBody(loginRequest!.data()).setMsgtype(Msg.Types.Login)
msg = try msgBuilder.build()
let (success, errmsg) = tcpsocket.send(data: encoder(msg!))
if success {
print("Send Successfully!")
} else {
print("Login Error: \(errmsg)")
}
} catch let e as NSError {
print("Login Request Function Error: \(e.localizedDescription)")
}
}
func encoder(msg: Msg) -> NSData {
let msgBytes = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(msg.data().bytes), count: msg.data().length))
let length = (UInt32)(msg.data().length)
var bigEndian = length.bigEndian
let bytePtr = withUnsafePointer(&bigEndian) {
UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: 4)
}
let lengthBytes = Array(bytePtr)
let request = lengthBytes + msgBytes
let requesttemp = NSData(bytes: request, length: (request.count))
return requesttemp
}
} |
//
// MoveComponent.swift
// GLplayground
//
// Created by Terna Kpamber on 4/14/17.
// Copyright © 2017 Terna Kpamber. All rights reserved.
//
import SceneKit
import GameplayKit
extension float3 {
var length: Float {
return sqrt(x*x + y*y + z*z)
}
}
class MoveComponent: GKAgent3D, GKAgentDelegate {
let entityManager: EntityManager!
init(maxSpeed: Float, maxAcceleration: Float, radius: Float, entityManager: EntityManager) {
self.entityManager = entityManager
super.init()
self.delegate = self
self.maxSpeed = maxSpeed
self.maxAcceleration = maxAcceleration
self.radius = radius
self.mass = 0.01
}
func agentWillUpdate(_ agent: GKAgent) {
guard let nodeComponent = entity?.component(ofType: NodeComponent.self) else {
return
}
let pos = nodeComponent.node.presentation.position
self.position = float3(pos)
}
func agentDidUpdate(_ agent: GKAgent) {
guard let nodeComponent = entity?.component(ofType: NodeComponent.self) else {
return
}
nodeComponent.node.position = vec3(self.position)
}
func closestMoveComponentForTeam(_ team: Team) -> GKAgent3D? {
let moveComponents = entityManager.moveComponentsForTeam(team)
var closestMoveComponent: GKAgent3D? = nil
var closestDistance: Float = MAXFLOAT
for component in moveComponents {
let distance = (self.position - component.position).length
if distance < closestDistance {
closestDistance = distance
closestMoveComponent = component
}
}
return closestMoveComponent
}
override func update(deltaTime seconds: TimeInterval) {
super.update(deltaTime: seconds)
guard
let entity = entity,
let teamComponent = entity.component(ofType: TeamComponent.self) else {
return
}
guard let enemyComponent = self.closestMoveComponentForTeam(teamComponent.team.opposite) else {
return
}
let allies = entityManager.moveComponentsForTeam(teamComponent.team)
self.behavior = MoveBehaviour(targetSpeed: self.maxSpeed, seek: enemyComponent, avoid: allies)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//: [Previous](@previous)
import Combine
class Temperature {
var value: Int
init(value: Int) {
self.value = value
}
}
class Weather {
@Published var temperature: Temperature = Temperature(value: 1)
}
let weather = Weather()
_ = weather.$temperature
.sink {
print ("Temperature now: \($0.value)")
}
weather.temperature.value = 2
print(weather.temperature.value)
//: [Next](@next)
|
//
// Command.swift
// ArgumentParser
//
// Created by Yume on 2020/3/10.
//
import ArgumentParser
import Foundation
import SitrepCore
struct Command: ParsableCommand {
@Option(name: [.short, .customLong("config")], help: "The path of `.sitrep.yml`.")
var configurationPath: String?
@Option(name: .shortAndLong, help: "The report format \(Scan.ReportType.args).")
var format: Scan.ReportType = .text
@Flag(name: [.customShort("i"), .customLong("info")], help: "Prints configuration information then exits.")
var showInfo = false
@Option(name: .shortAndLong, help: "The path of your project.")
var path = FileManager.default.currentDirectoryPath
func run() throws {
let configurationPath = self.configurationPath ?? self.path + "/.sitrep.yml"
let configuration: Configuration
if FileManager.default.fileExists(atPath: configurationPath) {
configuration = try Configuration.parse(configurationPath)
} else {
configuration = Configuration.default
}
if showInfo {
print("""
Configuration file: \(configurationPath)
Active settings: \(configuration)
Scan path: \(path)
""")
} else {
let url = URL(fileURLWithPath: path)
let app = Scan(rootURL: url)
app.run(reportType: self.format, configuration: configuration)
}
}
}
|
//
// Extensions.swift
// EscapeGame
//
// Created by admin on 08.02.15.
// Copyright (c) 2015 Sergey Simankov. All rights reserved.
//
import Foundation
import SpriteKit
extension CGVector
{
func length() -> CGFloat
{
return sqrt(self.dx * self.dx + self.dy * self.dy)
}
func normalize() -> CGVector
{
return CGVectorMake(self.dx/self.length(), self.dy/self.length())
}
}
|
../../StellarKit/source/Watches.swift |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.