blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
21bf3191550a655abebf8344f00bfb3901b84153
|
Swift
|
philip-github/SocialNetworkProject
|
/SocialNetworkProjectUpdated/Services/FirebaseServices 3.swift
|
UTF-8
| 15,868
| 2.53125
| 3
|
[] |
no_license
|
//
// FirebaseServices.swift
// SocialNetworkProjectUpdated
//
// Created by Philip Twal on 1/30/20.
// Copyright © 2020 Philip Twal. All rights reserved.
//
import Foundation
import UIKit
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase
class FirebaseServices {
static let shared = FirebaseServices()
private init() {}
let dataBaseRef = Database.database().reference()
typealias complition1 = (Error?) -> Void
typealias complition2 = (Data? , Error?) -> Void
func saveUserImage(img: UIImage, complitionHandler: @escaping complition1){
let user = Auth.auth().currentUser
let image = img
let imageData = image.jpegData(compressionQuality: 0)
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
let imageName = "UserImage/\(String(describing: user!.uid)).jpeg"
var storageRef = Storage.storage().reference()
storageRef = storageRef.child(imageName)
storageRef.putData(imageData!, metadata: metaData) { (data, error) in
complitionHandler(error)
}
}
func savePostImage(id: String, img: UIImage, complitionHandler: @escaping complition1){
let image = img
let imageData = image.jpegData(compressionQuality: 0)
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
let imageName = "PostsImages/\(String(describing: id)).jpeg"
var storageRef = Storage.storage().reference()
storageRef = storageRef.child(imageName)
storageRef.putData(imageData!, metadata: metaData) { (data, error) in
complitionHandler(error)
}
}
func getUserImage(complitionHandler : @escaping complition2){
let user = Auth.auth().currentUser
let imageName = "UserImage/\(String(describing: user!.uid)).jpeg"
var storageRef : StorageReference?
storageRef = Storage.storage().reference()
storageRef = storageRef?.child(imageName)
storageRef?.getData(maxSize: 1*1024*1024, completion: { (data, error) in
complitionHandler(data,error)
})
}
func signUp(user: UserModel, complitionHandler: @escaping complition1) {
Auth.auth().createUser(withEmail: user.email!, password: user.password!) { (data, error) in
if error == nil {
print("Creating a new user account !!")
let userDict = ["Username":user.userName!,"Email":user.email!] as [String: Any]
self.dataBaseRef.child("Users").child((data?.user.uid)!).setValue(userDict) { (error2, ref) in
complitionHandler(error2)
}
} else {
print("Somthing went wrong with creating user \(String(describing: error))")
}
}
}
func logIn(email: String, password: String ,complitionHandler: @escaping complition1){
Auth.auth().signIn(withEmail: email, password: password) { (data, error) in
complitionHandler(error)
}
}
func getUserImage(userId: String ,ComplitionHandler: @escaping complition2){
let imageName = "UserImage/\(userId).jpeg"
var storageRef : StorageReference?
storageRef = Storage.storage().reference()
storageRef = storageRef?.child(imageName)
storageRef?.getData(maxSize: 1*1024*1024, completion: { (data, error) in
ComplitionHandler(data,error)
})
}
func getUsers(complitionHandler : @escaping ([UserModel]?) -> Void){
let currentUser = Auth.auth().currentUser
let fetchUserGroup = DispatchGroup()
let fetchUserComponentsGroup = DispatchGroup()
fetchUserGroup.enter()
dataBaseRef.child("Users").observeSingleEvent(of: .value) { (snapShot,error) in
if error == nil {
var userArray = [UserModel]()
guard let snap = snapShot.value as? [String:Any] else {
print("Somthing went wrong getting snap shot \(String(describing: error))")
return
}
for record in snap {
let uid : String = record.key
if currentUser?.uid != uid{
let user = snap[uid] as? [String:Any]
var userModel = UserModel(userName: user!["Username"] as? String,
userId: uid,
password: nil,
userImg: nil,
email: user!["Email"] as? String)
fetchUserComponentsGroup.enter()
self.getUserImage(userId: uid) { (data, error) in
if error == nil{
userModel.userImg = UIImage(data: data!)
}else {print("Somthing went wrong with getting image \(String(describing: error))")}
userArray.append(userModel)
fetchUserComponentsGroup.leave()
}
}
}
fetchUserComponentsGroup.notify(queue: .main) {
fetchUserGroup.leave()
}
fetchUserGroup.notify(queue: .main) {
complitionHandler(userArray)
}
} else {
complitionHandler(nil)
}
}
}
func checkFriends(complitionHandler: @escaping ([String:Any]) -> Void){
let user = Auth.auth().currentUser?.uid
self.dataBaseRef.child("Users").child(user!).child("FriendsList").observeSingleEvent(of: .value) { (snapShot,error) in
guard let friends = snapShot.value as? [String:Any] else{
print("Somthing went wrong OR no friends found!")
return
}
complitionHandler(friends)
}
}
func getFriends(complitionHandler : @escaping ([UserModel]?) -> Void){
let user = Auth.auth().currentUser
var friendArray : [UserModel] = []
let friendListDispatchGroup = DispatchGroup()
self.dataBaseRef.child("Users").child(user!.uid).child("FriendsList").observeSingleEvent(of: .value) { (friendsSnapShot) in
if let friends = friendsSnapShot.value as? [String:Any]{
for friend in friends{
friendListDispatchGroup.enter()
self.dataBaseRef.child("Users").child(friend.key).observeSingleEvent(of: .value) { (snapShot) in
guard let singleFriend = snapShot.value as? Dictionary<String,Any> else {return}
var userModel = UserModel(userName: singleFriend["Username"] as? String,
userId: friend.key,
password: nil,
userImg: nil,
email: singleFriend["Email"] as? String)
self.getUserImage(userId: userModel.userId!) { (data, error) in
if error == nil {
userModel.userImg = UIImage(data: data!)
}
friendArray.append(userModel)
friendListDispatchGroup.leave()
}
}
}
friendListDispatchGroup.notify(queue: .main) {
complitionHandler(friendArray)
}
} else {
complitionHandler(nil)
}
}
}
func addPost(img: UIImage ,postDesc: String?, complitionHandler: @escaping complition1){
let user = Auth.auth().currentUser
let postKey = self.dataBaseRef.child("Posts").childByAutoId().key
let postDict = ["UserId": user?.uid, "PostDescription": postDesc ?? "" , "TimeStamp": "\(NSDate().timeIntervalSince1970)"]
self.dataBaseRef.child("Posts").child(postKey!).setValue(postDict) { (error, ref) in
if error == nil {
self.savePostImage(id: postKey!, img: img) { (error) in
if error == nil {
complitionHandler(nil)
}else{
print("Somthin went wrong saving image to storage")
}
}
}else{
print("Somthing went wrong adding post to database")
}
}
}
func getUserById(userId: String, complitionHandler: @escaping (UserModel) -> Void){
self.dataBaseRef.child("Users").child(userId).observeSingleEvent(of: .value) { (snapShot) in
guard let snap = snapShot.value as? [String:Any] else {
print("Somthing went wrong fetching user by id")
return
}
self.getUserImage(userId: userId) { (data, error) in
if error == nil{
let use = UserModel(userName: snap["Username"] as? String, userId: userId, password: nil, userImg: UIImage(data: data ?? Data()), email: snap["Email"] as? String )
complitionHandler(use)
}else{
print("Somthing went wrong fetching user image")
}
}
}
}
func getPostImg(id: String, complitionHandler: @escaping complition2){
let imageName = "PostsImages/\(String(describing: id)).jpeg"
var storageRef = StorageReference()
storageRef = Storage.storage().reference()
storageRef = storageRef.child(imageName)
storageRef.getData(maxSize: 1*1024*1024) { (data, error) in
complitionHandler(data,error)
}
}
func getPosts(complitionHandler: @escaping ([[String:Any]]?) -> Void){
let mainDispatchGroup = DispatchGroup()
let fetchPostsListDispatch = DispatchGroup()
var postArr = [[String:Any]]()
self.dataBaseRef.child("Posts").observeSingleEvent(of: .value) { (snapShot) in
guard let snap = snapShot.value as? Dictionary<String,Any> else {
print("Somthing went wrong fetching posts from data base")
return
}
mainDispatchGroup.enter()
for record in snap{
fetchPostsListDispatch.enter()
let key = record.key
let post = snap[key] as! [String:Any]
var postDict = ["userId":post["UserId"]!,
"comment":post["PostDescription"]!,
"timestamp":post["TimeStamp"]!,
"postImg": nil,
"userName": nil,
"userImg": nil]
self.getPostImg(id: key) { (data, error) in
if error == nil && data != nil {
let image = UIImage(data: data!)
postDict["postImg"] = image
}else{
print("Somthing went wrong fetching post image \(String(describing: error?.localizedDescription))")
}
}
self.getUserById(userId: postDict["userId"] as! String) { (userArray) in
postDict["userName"] = userArray.userName
postDict["userImg"] = userArray.userImg
postArr.append(postDict as [String : Any])
fetchPostsListDispatch.leave()
}
}
fetchPostsListDispatch.notify(queue: .main){
mainDispatchGroup.leave()
}
mainDispatchGroup.notify(queue: .main){
complitionHandler(postArr)
}
}
}
func addFreind(friendId : String, complitionHandler : @escaping complition1){
let user = Auth.auth().currentUser
self.dataBaseRef.child("Users").child(user!.uid).child("FriendsList").updateChildValues([friendId : "FriendID"]) {
(error, ref) in
complitionHandler(error)
}
}
func removeFriend(friendId: String ,complitionHandler: @escaping complition1){
let user = Auth.auth().currentUser
self.dataBaseRef.child("Users").child(user!.uid).child("FriendsList").child(friendId).removeValue() { (error, ref) in
complitionHandler(error)
}
}
func sendMessage(friendId: String, messageText: String, complitionHandler: @escaping complition1){
let user = Auth.auth().currentUser
let sentMessageDict = ["Message": messageText, "TimeStamp":"\(NSDate().timeIntervalSince1970)","MessageType":"Sent"]
let recievedMessageDict = ["Message": messageText, "TimeStamp":"\(NSDate().timeIntervalSince1970)","MessageType":"Recived"]
self.dataBaseRef.child("Conversations").child(user!.uid).child("Chat").child(friendId).childByAutoId().setValue(sentMessageDict) { (error, ref) in
if error == nil{
complitionHandler(nil)
print("sent Message inserted in data base")
}
}
self.dataBaseRef.child("Conversations").child(friendId).child("Chat").child(user!.uid).childByAutoId().setValue(recievedMessageDict) { (error, ref) in
if error == nil {
complitionHandler(nil)
print("recieved Message inserted in data base")
}
}
}
func getMessages(friendId: String, complitionHandler: @escaping ([ConversationModel]?) -> Void){
let fetchChatListDispatch = DispatchGroup()
let user = Auth.auth().currentUser
var chatArray = [ConversationModel]()
self.dataBaseRef.child("Conversations").child(user!.uid).child("Chat").child(friendId).observeSingleEvent(of: .value) { (snapShot) in
guard let myChat = snapShot.value as? Dictionary<String,Any> else {
print("Somthing went wrong !!")
return
}
fetchChatListDispatch.enter()
for chat in myChat{
let key = chat.key
let conversation = myChat[key] as? [String:Any]
let convModel = ConversationModel(userId: user!.uid,
friendId: friendId,
message: conversation?["Message"]! as? String,
time: conversation?["TimeStamp"]! as? String,
senderImage: nil,
reciverImage: nil)
chatArray.append(convModel)
print(chatArray)
}
fetchChatListDispatch.leave()
fetchChatListDispatch.notify(queue: .main){
complitionHandler(chatArray)
}
}
}
}
| true
|
2cae2d9f5dd7bcd71ce901aca29de38d6b0979fb
|
Swift
|
drewag/Q-and-A
|
/KeyboardFieldPrompt/Final/KeyboardFieldPrompt/KeyboardFieldPromptController.swift
|
UTF-8
| 4,566
| 2.65625
| 3
|
[] |
no_license
|
//
// KeyboardFieldPromptController.swift
// KeyboardFieldPrompt
//
// Created by Andrew J Wagner on 9/1/19.
// Copyright © 2019 Drewag. All rights reserved.
//
import UIKit
class KeyboardFieldPromptController: UIViewController {
// View to hold the text field above the keyboard
let aboveKeyboardView = UIView()
let textField = UITextField()
let keyboadConstraintAdjuster = KeyboardConstraintAdjuster()
let completion: (String) -> ()
let configure: (UITextField) -> ()
init(
configure: @escaping (UITextField) -> () = { _ in },
completion: @escaping (String) -> ()
)
{
self.completion = completion
self.configure = configure
super.init(nibName: nil, bundle: nil)
// Configure as overlay
self.modalPresentationStyle = .overFullScreen
self.modalTransitionStyle = .crossDissolve
}
override func viewDidLoad() {
super.viewDidLoad()
// -----------------
// Dismiss on tap
// -----------------
let recognizer = UITapGestureRecognizer(target: self, action: #selector(tapToDismiss))
self.view.addGestureRecognizer(recognizer)
// -----------------
// Configure the views
// -----------------
self.view.backgroundColor = UIColor(white: 0, alpha: 0.2)
self.aboveKeyboardView.backgroundColor = UIColor.white
self.textField.returnKeyType = .done
self.textField.delegate = self
self.configure(self.textField)
self.aboveKeyboardView.addSubview(self.textField)
self.view.addSubview(self.aboveKeyboardView)
// -----------------
// Constrain textField to inside of aboveKeyboardView
// -----------------
var factory = ConstraintFactory()
self.textField.translatesAutoresizingMaskIntoConstraints = false
factory.constrain([.centerX, .top, .bottom], ofBoth: self.textField, and: self.aboveKeyboardView)
factory.constrain(.height, of: self.textField, to: 44)
// Constrain the sides to the safe area
factory.add(self.view.safeAreaLayoutGuide.leftAnchor.constraint(
equalTo: self.textField.leftAnchor,
constant: -8
))
// This is the complicated part to handle the safe area
// By default, the aboveKeyboardView should be tall enough to fit the text field
let fill = factory.constrain(.bottom, ofBoth: self.textField, and: self.aboveKeyboardView)
// Set its priority to low to make it breakable
fill.priority = .defaultLow
// More importantly, space should be left at the bottom greater than or equal to the safe area
factory.add(self.view.safeAreaLayoutGuide.bottomAnchor.constraint(greaterThanOrEqualTo: self.textField.bottomAnchor))
// -----------------
// Constrain the aboveKeyboardView view to the bottom of the view above the keyboard
// -----------------
self.aboveKeyboardView.translatesAutoresizingMaskIntoConstraints = false
factory.constrain([.left, .right], ofBoth: self.view!, and: self.aboveKeyboardView)
self.keyboadConstraintAdjuster.view = self.view
self.keyboadConstraintAdjuster.constraint = factory.constrain(.bottom, ofBoth: self.view!, and: self.aboveKeyboardView)
// -----------------
// Activate all of the constraints
// -----------------
factory.activateAll()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async {
// Become first responder on the next main loop
// to avoid weird presentation animation
self.textField.becomeFirstResponder()
let range = self.textField.textRange(
from: self.textField.endOfDocument,
to: self.textField.endOfDocument
)
self.textField.selectedTextRange = range
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func tapToDismiss() {
// Resign first responder first to create smoother dismiss animation
self.textField.resignFirstResponder()
self.dismiss(animated: true, completion: nil)
}
}
extension KeyboardFieldPromptController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.tapToDismiss()
self.completion(textField.text ?? "")
return false
}
}
| true
|
2b3814e6db4e3be09b451337b5bfd06c4da380d5
|
Swift
|
pengfei2015/PFSwiftExtension
|
/Sources/Collection+PFExtension.swift
|
UTF-8
| 927
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// CollectionType+Extension.swift
// Extensions
//
// Created by 飞流 on 2017/11/10.
// Copyright © 2017年 飞流. All rights reserved.
//
import UIKit
extension Collection {
func mergeIntoSections(_ canMergeTogether: (Self.Iterator.Element, Self.Iterator.Element) -> Bool) -> [[Self.Iterator.Element]] {
var sections: [[Self.Iterator.Element]] = []
self.forEach { element in
var index: Int?
sections.enumerated().forEach { i, e in
if canMergeTogether(e.first!, element) {
index = i
return
}
}
if let i = index {
var section = sections.remove(at: i)
section.append(element)
sections.insert(section, at: i)
} else {
sections.append([element])
}
}
return sections
}
}
| true
|
a66f847b1667944de80e257e93f9f24dd02fac77
|
Swift
|
trinhttt/OnboardingAndBanner
|
/TestScrollView/Model/OnboardingItem.swift
|
UTF-8
| 902
| 2.703125
| 3
|
[] |
no_license
|
//
// OnboardingItem.swift
// TestScrollView
//
// Created by Trinh Thai on 9/14/20.
// Copyright © 2020 Trinh Thai. All rights reserved.
//
import UIKit
struct OnboardingItem {
let title: String
let detail: String
let image: UIImage?
static let placeholderItems: [OnboardingItem] = [
.init(title: "Title1",
detail: "\"T1 \n T1 \n T1\"",
image: UIImage(named: "0")),
.init(title: "Title2",
detail: "\"T2 \n T2 \n T2\"",
image: UIImage(named: "1")),
.init(title: "Title3",
detail: "\"T3 \n T3 \n T3\"",
image: UIImage(named: "2")),
.init(title: "Title4",
detail: "\"T4 \n T4 \n T4\"",
image: UIImage(named: "3")),
.init(title: "Title5",
detail: "\"T5 \n T5 \n T5\"",
image: UIImage(named: "4"))
]
}
| true
|
815fce3eb7ba96303746f76733e430ae2d3eb7f3
|
Swift
|
ErwanHesry/SW_Test
|
/MobileChallenge/Scenes/BookmarksScene/BookmarksCoordinator.swift
|
UTF-8
| 1,979
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// BookmarksCoordinator.swift
// MobileChallenge
//
// Created by Erwan Hesry on 10/03/2021.
//
import UIKit
class BookmarksCoordinator:Coordinator {
// MARK: - Properties
let networkService: NetworkService
let rootViewController: UINavigationController
let storyboard = UIStoryboard.init(name: "Bookmarks", bundle: nil)
var delegate: CoordinatorDelegate? = nil
init(rootViewController: UINavigationController, networkService:NetworkService) {
self.networkService = networkService
self.rootViewController = rootViewController
self.rootViewController.tabBarItem.image = UIImage(systemName: "book.circle")
self.rootViewController.tabBarItem.selectedImage = UIImage(systemName: "book.circle.fill")
self.rootViewController.tabBarItem.title = "tabBarItem".localize("Bookmarks")
}
// MARK: - Coordinator overrides
override func start() {
let bookmarksVC: BookmarksViewController = storyboard.instantiateInitialViewController() as! BookmarksViewController
let viewModel = BookmarksViewModel(networkService: self.networkService)
viewModel.coordinatorDelegate = self
bookmarksVC.viewModel = viewModel
self.rootViewController.viewControllers=[bookmarksVC]
}
override func finish() {
self.delegate?.didFinish(from: self)
}
}
extension BookmarksCoordinator: BookmarksViewModelCoordinatorDelegate {
func goToArtist(_ artistId: String, _ artistName: String) {
let artistCoordinator = ArtistCoordinator.init(navigationController: self.rootViewController, networkService: self.networkService)
artistCoordinator.delegate = self
addChildCoordinator(artistCoordinator)
artistCoordinator.startWith(artistId, artistName: artistName)
}
}
extension BookmarksCoordinator: CoordinatorDelegate {
func didFinish(from coordinator: Coordinator) {
removeChildCoordinator(coordinator)
}
}
| true
|
8dec37df1073d893d0592564c01fa9bbef8d17e6
|
Swift
|
JFerrer95/ios-sprint3-challenge
|
/Pokemon/Okemon/PokemonController.swift
|
UTF-8
| 2,445
| 3.28125
| 3
|
[] |
no_license
|
//
// PokemonController.swift
// Okemon
//
// Created by Jonathan Ferrer on 5/17/19.
// Copyright © 2019 Jonathan Ferrer. All rights reserved.
//
import UIKit
class PokemonController {
var pokemons: [Pokemon] = []
var pokemon: Pokemon?
static let baseURL = URL(string: "https://pokeapi.co/api/v2/pokemon/")!
func addPokemon(name: String, id: Int, abilities: [Ability], types: [Types], sprites: Sprite) {
let pokemon = Pokemon(name: name, id: id, abilities: abilities, types: types, sprites: sprites)
pokemons.append(pokemon)
}
func getImage(image: String, completion: @escaping (UIImage?, Error?) -> Void) {
let imageURL = URL(string: image)!
var requestURL = URLRequest(url: imageURL)
requestURL.httpMethod = HTTPMethod.get.rawValue
URLSession.shared.dataTask(with: requestURL) { (data, _, error) in
if let error = error {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError())
return
}
let image = UIImage(data: data)!
completion(image, nil)
}.resume()
}
func searchPokemon(with searchTerm: String, completion: @escaping (Error?) -> Void) {
let requestURL = PokemonController.baseURL.appendingPathComponent(searchTerm.lowercased())
var request = URLRequest(url: requestURL)
request.httpMethod = HTTPMethod.get.rawValue
URLSession.shared.dataTask(with: request) { (data, _, error) in
if let error = error {
NSLog("Error fetching pokemon: \(error)")
completion(error)
return
}
guard let data = data else {
NSLog("No data returned from dataTask")
completion(error)
return
}
let decoder = JSONDecoder()
do {
let pokemonSearch = try decoder.decode(Pokemon.self, from: data)
self.pokemon = pokemonSearch
completion(nil)
} catch {
NSLog("Error decoding pokemon: \(error)")
completion(error)
}
}.resume()
}
enum HTTPMethod: String {
case get = "GET"
case put = "PUT"
case post = "POST"
case delete = "DELETE"
}
}
| true
|
e5f554b98f017d5c1592ba3365c44194a2a7369d
|
Swift
|
almighty-ken/iOS_gale
|
/Gale/Gale/SignUpViewController.swift
|
UTF-8
| 5,452
| 2.609375
| 3
|
[] |
no_license
|
//
// SignUpViewController.swift
// Gale
//
// Created by Ken Cheng on 11/27/16.
// Copyright © 2016 cpsc437. All rights reserved.
//
import UIKit
import SwiftyJSON
class SignUpViewController: UIViewController {
@IBOutlet weak var user_name: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var displayed_name: UITextField!
var jwt: String!
@IBAction func sign_up(_ sender: Any) {
let url:URL = URL(string: "http://localhost:4000/api/user")!
var request = URLRequest(url: url)
// var responseObject : [String:Any]!
let dictionary: [String:String]
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
//request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.httpMethod = "POST"
dictionary = ["username": user_name.text!, "password": password.text!,"name":displayed_name.text!]
request.httpBody = try! JSONSerialization.data(withJSONObject: dictionary)
let task_create = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error!) // some fundamental network error
return
}
// do {
// responseObject = try JSONSerialization.jsonObject(with: data) as? [String:Any]
// print(responseObject)
// if (responseObject["error"] as? String == "1"){
// print("create user fail")
// }else{
// print("user created")
// self.login(user_name: self.user_name.text!,user_password: self.password.text!)
//
////
// }
// } catch let jsonError {
// print(jsonError)
// print(String(data: data, encoding: .utf8)!) // often the `data` contains informative description of the nature of the error, so let's look at that, too
// }
let response = JSON(data:data)
if(response["error"]==true){
print("user create fail")
}else{
print("user created")
self.login(user_name: self.user_name.text!,user_password: self.password.text!)
}
}
task_create.resume()
}
func login(user_name:String, user_password:String){
let url:URL = URL(string: "http://localhost:4000/api/login")!
var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
//request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.httpMethod = "POST"
let dictionary = ["username": user_name, "password": user_password]
request.httpBody = try! JSONSerialization.data(withJSONObject: dictionary)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error!) // some fundamental network error
return
}
do {
let responseObject = try JSONSerialization.jsonObject(with: data) as? [String: Any]
if let payload = responseObject?["payload"] as? [String: Any]{
if let jwt = payload["jwt"] as? String{
// print(jwt)
DispatchQueue.main.async {
self.jwt = jwt
self.performSegue(withIdentifier: "signup_jwt", sender: nil)
}
}
}
// print(responseObject[payload][jwt])
// jwt = responseObject.payload.jwt
} catch let jsonError {
print(jsonError)
print(String(data: data, encoding: .utf8)!) // often the `data` contains informative description of the nature of the error, so let's look at that, too
}
}
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//print("preparing segue")
if segue.identifier == "signup_jwt"{
print("passing jwt")
let destVc = segue.destination as? CreateEventViewController
destVc!.jwt = jwt
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
60ea49c20bfa578aa3b6d3de2f2139bf95564abe
|
Swift
|
FlyRicardo/MeLiCodeChallenge
|
/MeLiCodeChallenge/MeLiCodeChallenge/Views/ProductDetail/Presenter/ProductDetailPresenter.swift
|
UTF-8
| 1,968
| 2.984375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ProductDetailPresenter.swift
// MeLiCodeChallenge
//
// Created by Fabián Ricardo Rodríguez Avellaneda on 24/06/21.
//
import Foundation
class ProductDetailPresenter {
private var productDetailAdapter: ProductDetailAdapterProtocol
private var view: ProductDetailViewProtocol
private var error: NetworkingError
private var errorLoadingData: Bool
init(productDetailAdapter: ProductDetailAdapterProtocol,
view: ProductDetailViewProtocol) {
self.productDetailAdapter = productDetailAdapter
self.view = view
self.error = .cancelled
self.errorLoadingData = false
}
}
//MARK: ProductPresenterProtocol
extension ProductDetailPresenter: ProductDetailPresenterProtocol {
func loadProductDetail(byProductId productId: String) {
productDetailAdapter.fetchProductsDetail(byProductId: productId) { [weak self] (result: Result<ProductDetailModel, NetworkingError>) in
guard let self = self else {
return
}
switch result {
case .success(let productDetail):
self.handleCompletionProductApiCall(response: productDetail)
case .failure(let error):
self.handleErrorWhenLoadingData(error.localizedDescription)
}
}
}
}
// MARK: - Propagate view states
extension ProductDetailPresenter {
private func handleCompletionProductApiCall(response: ProductDetailModel) {
view.refreshProductDetail(data: response)
view.isLoadingObservable = false
}
private func handleErrorWhenLoadingData(_ errorDescription: String) {
view.showErrorObservable = true
}
private func errorDescription(_ error: NetworkingError) -> String {
guard error.localizedDescription.isEmpty else {
return Constants.Categories.Localizable.alertErrorDescription
}
return error.localizedDescription
}
}
| true
|
ba5735fd2ef8b9fe21f2f70f6542988ef82a23c7
|
Swift
|
ricoh-brossman/CIP-SSE_TeamStatus
|
/TeamStatus/RevenueViewController.swift
|
UTF-8
| 7,441
| 2.53125
| 3
|
[] |
no_license
|
//
// RevenueViewController.swift
// TeamStatus
//
// Created by craig.brossman@ricoh-usa.com on 2/14/18.
// Copyright © 2018 craig.brossman@ricoh-usa.com. All rights reserved.
//
import UIKit
import AWSAuthCore
import AWSAuthUI
let MonthlyPropertyLabels = [
["Core Services", "Misc Services", "Total"],
["Plan", "Margin", "Attainment"],
["YTD Actual", "Plan", "Margin", "Attainment"]]
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
class RevenueViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var revenueJSON: Revenue?
var revMonthIndex = 0
@IBOutlet weak var revTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// if !AWSSignInManager.sharedInstance().isLoggedIn {
//// let config = AWSAuthUIConfiguration()
// AWSAuthUIViewController.presentViewController(with: self.navigationController!, configuration: nil, completionHandler: { (provider: AWSSignInProvider, error: Error?) in
// if error != nil {
// print("Error occured: \(String(describing: error))")
// }
// else {
//
// }
// })
// }
self.navigationItem.title = self.revenueJSON?.month[revMonthIndex].date
revTableView.delegate = self
revTableView.dataSource = self
if (revMonthIndex + 1) >= (self.revenueJSON?.month.count)! {
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
}
@IBAction func nextMonthRev(_ sender: UIBarButtonItem) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nextRevVC = storyboard.instantiateViewController(withIdentifier: "RevenueViewController") as! RevenueViewController
nextRevVC.revenueJSON = self.revenueJSON
nextRevVC.revMonthIndex = self.revMonthIndex + 1
self.navigationController?.pushViewController(nextRevVC, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section) {
case 0:
return 3
case 1:
return 3
case 2:
return 4
default:
return 4
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch (section) {
case 0:
return "Actual Monthly Revenue"
case 1:
return "Actual vs Plan Revenue"
case 2:
return "YTD vs Plan Revenue"
default:
return "something went wrong"
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = revTableView.dequeueReusableCell(withIdentifier: "RevenueTableViewCell", for: indexPath) as! RevenueTableViewCell
let month = self.revenueJSON?.month[revMonthIndex]
cell.propertyLabel.text = MonthlyPropertyLabels[indexPath.section][indexPath.row]
var val: Int?
var isPercentage = false
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
val = month?.actuals.coreServices
case 1:
val = month?.actuals.miscServices
default:
val = month?.actuals.total
}
case 1:
switch (indexPath.row) {
case 0:
val = month?.monthVsPlan.plan
case 1:
val = month?.monthVsPlan.MvsP
default:
val = month?.monthVsPlan.attainment
isPercentage = true
}
default:
switch (indexPath.row) {
case 0:
val = month?.ytdVsPlan.actual
case 1:
val = month?.ytdVsPlan.plan
case 2:
val = month?.ytdVsPlan.YTDvsP
default:
val = month?.ytdVsPlan.attainment
isPercentage = true
}
}
if isPercentage {
cell.valueText.text = String(val!) + "%"
}
else {
cell.valueText.text = currencyFormatter.string(from: NSNumber(value: val!))
}
if val! < 0 || (isPercentage && val! < 100){
cell.valueText.textColor = UIColor.red
}
else {
cell.valueText.textColor = UIColor(hexString: "57984F")
// (displayP3Red: 0x57, green: 0x98, blue: 0x4f, alpha: 0xff)
}
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
let ytdLauncher = YTDLauncher()
@IBAction func YTDPressed(_ sender: UIButton) {
ytdLauncher.ytdJSON = revenueJSON?.ytdTotals
ytdLauncher.showYTD()
}
// @IBAction func YTDButton(_ sender: UIButton) {
// ytdLauncher.ytdJSON = revenueJSON?.ytdTotals
// ytdLauncher.showYTD()
// }
//
// let blackView = UIView()
//
// func handleYTDTotal() {
// if let window = UIApplication.shared.keyWindow {
// blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
//
// blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(RevenueViewController.handleDismiss(_ :))))
// // #selector(handleDismiss(_:))))
//
// view.addSubview(blackView)
// blackView.alpha = 0.0
// blackView.frame = window.frame
//
// UIView.animate(withDuration: 0.5, animations: {
// self.blackView.alpha = 1.0
// })
// }
// }
//
// // @objc func handleDismiss(_ sender: UIGestureRecognizer) {
// @objc func handleDismiss(_ sender: UITapGestureRecognizer) {
// UIView.animate(withDuration: 0.5) {
// self.blackView.alpha = 0.0
// }
// }
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
87c35a90b7d67f2912425d382cd0db5d9ba6f425
|
Swift
|
topzerzar/weather
|
/KrugsriWeather/Model/CurrentWeatherModel.swift
|
UTF-8
| 671
| 2.796875
| 3
|
[] |
no_license
|
//
// Weather.swift
// KrugsriWeather
//
// Created by weerapon on 18/5/2564 BE.
//
import SwiftyJSON
class CurrentWeatherModel {
var id: NSNumber?
var cityName: String?
var timezone: NSNumber?
var detail: MainTemperatureModel?
var weather: [WeatherModel]?
init(from json: JSON) {
self.id = json["id"].number
self.cityName = json["name"].string
self.timezone = json["timezone"].number
self.detail = MainTemperatureModel(from: json["main"])
self.weather = json["weather"].arrayValue.compactMap { (item) -> WeatherModel in
return WeatherModel(from: item)
}
}
}
| true
|
ebc05abd0dfcaa69fc91699e60abd110b5f885cf
|
Swift
|
ricksimon/DereGuide
|
/DereGuide/Model/CGSSLiveDetail.swift
|
UTF-8
| 3,720
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// TableViewCell.swift
// DereGuide
//
// Created by zzk on 2017/5/16.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import SwiftyJSON
enum CGSSLiveDifficulty: Int, CustomStringConvertible, ColorRepresentable {
case debut = 1
case regular
case pro
case master
case masterPlus
case legacyMasterPlus = 101
case light = 11
case trick = 12
static let all: [CGSSLiveDifficulty] = [CGSSLiveDifficulty.debut, .regular, .pro, .master, .masterPlus, .legacyMasterPlus, .light, .trick]
var description: String {
switch self {
case .debut:
return "DEBUT"
case .regular:
return "REGULAR"
case .pro:
return "PRO"
case .master:
return "MASTER"
case .masterPlus:
return "MASTER+"
case .legacyMasterPlus:
return "LEGACY MASTER+"
case .light:
return "LIGHT"
case .trick:
return "TRICK"
}
}
var color: UIColor {
switch self {
case .debut:
return .debut
case .regular:
return .regular
case .pro:
return .pro
case .master:
return .master
case .masterPlus:
return .masterPlus
case .legacyMasterPlus:
return .legacyMasterPlus
case .light:
return .light
case .trick:
return .trick
}
}
var difficultyTypes: CGSSLiveDifficultyTypes {
return CGSSLiveDifficultyTypes.init(difficulty: self)
}
}
struct CGSSLiveDifficultyTypes: OptionSet {
let rawValue: UInt
init(rawValue: UInt) { self.rawValue = rawValue }
static let debut = CGSSLiveDifficultyTypes.init(rawValue: 1 << 0)
static let regular = CGSSLiveDifficultyTypes.init(rawValue: 1 << 1)
static let pro = CGSSLiveDifficultyTypes.init(rawValue: 1 << 2)
static let master = CGSSLiveDifficultyTypes.init(rawValue: 1 << 3)
static let masterPlus = CGSSLiveDifficultyTypes.init(rawValue: 1 << 4)
static let legacyMasterPlus = CGSSLiveDifficultyTypes.init(rawValue: 1 << 5)
static let light = CGSSLiveDifficultyTypes.init(rawValue: 1 << 6)
static let trick = CGSSLiveDifficultyTypes.init(rawValue: 1 << 7)
static let all = CGSSLiveDifficultyTypes.init(rawValue: 0b11111111)
init(difficulty: CGSSLiveDifficulty) {
switch difficulty {
case .debut:
self = .debut
case .regular:
self = .regular
case .pro:
self = .pro
case .master:
self = .master
case .masterPlus:
self = .masterPlus
case .legacyMasterPlus:
self = .legacyMasterPlus
case .light:
self = .light
case .trick:
self = .trick
}
}
}
extension CGSSLiveDetail {
var difficultyTypes: CGSSLiveDifficultyTypes {
return CGSSLiveDifficultyTypes(difficulty: difficulty)
}
}
struct CGSSLiveDetail {
var id: Int
var difficulty: CGSSLiveDifficulty
var liveID: Int
var stars: Int
var numberOfNotes: Int
var rankSCondition: Int
init?(fromJson json: JSON) {
guard let difficulty = CGSSLiveDifficulty(rawValue: json["difficulty_type"].intValue) else { return nil }
id = json["id"].intValue
liveID = json["live_data_id"].intValue
self.difficulty = difficulty
stars = json["stars_number"].intValue
numberOfNotes = json["live_notes_number"].intValue
rankSCondition = json["rank_s_condition"].intValue
}
}
| true
|
29d56ca1a60747551eb3fde67cc57756f9939410
|
Swift
|
mitchtreece/Espresso
|
/Sources/UI/UIKit/Views/UINibView.swift
|
UTF-8
| 752
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// UINibView.swift
// Espresso
//
// Created by Mitch Treece on 7/5/18.
//
import UIKit
/// `UIView` subclass that loads it's contents from a nib.
open class UINibView: UIBaseView {
/// Initializes a new instance of the view from a nib. If no name is provided, the class name will be used.
///
/// - Parameter name: The nib's name.
/// - Parameter bundle: The bundle to load the nib from; _defaults to Bundle.main_.
/// - Returns: A typed nib-loaded view instance.
public static func initFromNib(named name: String? = nil,
in bundle: Bundle = Bundle.main) -> Self {
return loadFromNib(
name: name,
bundle: bundle
)
}
}
| true
|
0af41dc0fab8959a2844ca26ca3c93caf09207a9
|
Swift
|
joachimneumann/gmpcalculator-
|
/Calculator/NumberStack.swift
|
UTF-8
| 1,171
| 3.515625
| 4
|
[] |
no_license
|
//
// NumberStack.swift
// Calculator
//
// Created by Joachim Neumann on 29/09/2021.
//
import Foundation
struct NumberStack: CustomDebugStringConvertible{
private var array: [Number] = []
var count: Int {
assert(array.count > 0)
return array.count
}
var last: Number {
assert(array.count > 0)
return array.last!
}
mutating func replaceLast(with number: Number) {
removeLast()
append(number)
}
mutating func append(_ number: Number) {
array.append(number)
}
mutating func popLast() -> Number {
assert(array.count > 0)
return array.popLast()!
}
mutating func removeLast() {
assert(array.count > 0)
array.removeLast()
}
mutating func removeAll() {
array.removeAll()
}
var secondLast: Number? {
if count >= 2 {
return array[array.count - 2]
} else {
return nil
}
}
var debugDescription: String {
var ret = "numberStack \(array.count): "
for number in array {
ret += "\(number) "
}
return ret
}
}
| true
|
f475120266d22360d12f5d98954bd3332289a131
|
Swift
|
Michae1Nechaev/SmashingFlashing
|
/SmashingFlashing/Models/Cutter.swift
|
UTF-8
| 4,019
| 2.6875
| 3
|
[] |
no_license
|
//
// Cutter.swift
// SmashingFlashing
//
// Created by Михаил Нечаев on 18.01.18.
// Copyright © 2018 Михаил Нечаев. All rights reserved.
//
import Foundation
import AVFoundation
import Photos
class Cutter {
let startTime: CMTime
let endTime: CMTime
let sourceURL: URL
init(start: Double, end: Double, url: URL) {
startTime = CMTime.init(seconds: start, preferredTimescale: 1)
endTime = CMTime.init(seconds: end, preferredTimescale: 1)
sourceURL = url
}
func cutVideo(completion: @escaping () -> Void) {
let docsURL = DocsDirectory.path
let destinationURL = docsURL.appendingPathComponent("video_\(arc4random_uniform(1000)).mov")! as URL
let options = [
AVURLAssetPreferPreciseDurationAndTimingKey: true
]
let asset = AVURLAsset(url: sourceURL, options: options)
let preferredPreset = AVAssetExportPresetPassthrough
if verifyPresetForAsset(preset: preferredPreset, asset: asset) {
let composition = AVMutableComposition()
let videoCompTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: CMPersistentTrackID())
let audioCompTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: CMPersistentTrackID())
guard let assetVideoTrack: AVAssetTrack = asset.tracks(withMediaType: .video).first else { return }
guard let assetAudioTrack: AVAssetTrack = asset.tracks(withMediaType: .audio).first else { return }
var accumulatedTime = kCMTimeZero
let durationOfCurrentSlice = CMTimeSubtract(endTime, startTime)
let timeRangeForCurrentSlice = CMTimeRangeMake(startTime, durationOfCurrentSlice)
do {
try videoCompTrack!.insertTimeRange(timeRangeForCurrentSlice, of: assetVideoTrack, at: accumulatedTime)
try audioCompTrack!.insertTimeRange(timeRangeForCurrentSlice, of: assetAudioTrack, at: accumulatedTime)
accumulatedTime = CMTimeAdd(accumulatedTime, durationOfCurrentSlice)
}
catch let compError {
print("TrimVideo: error during composition: \(compError)")
}
guard let exportSession = AVAssetExportSession(asset: composition, presetName: preferredPreset) else { return }
exportSession.outputURL = destinationURL as URL
exportSession.outputFileType = AVFileType.mov
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously { () -> Void in
switch exportSession.status {
case AVAssetExportSessionStatus.completed:
print("-----Cut video exportation complete.\(String(describing: destinationURL))")
PhotoLibraryManager.exportToPhotoLibraryAssetWith(url: destinationURL)
Helper().removeFileAtURLIfExists(url: destinationURL)
completion()
case AVAssetExportSessionStatus.failed:
print("failed \(String(describing: exportSession.error))")
case AVAssetExportSessionStatus.cancelled:
print("cancelled \(String(describing: exportSession.error))")
default:
print("complete")
print("\(String(describing: destinationURL))")
}
}
}
else {
print("TrimVideo - Could not find a suitable export preset for the input video")
}
}
func verifyPresetForAsset(preset: String, asset: AVAsset) -> Bool {
let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: asset)
let filteredPresets = compatiblePresets.filter { $0 == preset }
return filteredPresets.count > 0 || preset == AVAssetExportPresetPassthrough
}
}
| true
|
a745b4b985838f7f20220d181c9dbf39914b8d77
|
Swift
|
Ludraig/GME-Sim
|
/GME Sim/Order.swift
|
UTF-8
| 1,488
| 2.84375
| 3
|
[] |
no_license
|
import Foundation
class Order: Identifiable {
var id: String!
var customerId: String!
var orderItems: [Article] = []
var amount: Double!
var customerName: String!
var isCompleted: Bool!
func saveOrderToFirestore() {
FirebaseReference(.Order).document(self.id).setData(orderDictionaryFrom(self))
{
error in
if error != nil {
print("error saving order to firestore: ", error!.localizedDescription)
}
}
}
}
// création de la commande
func orderDictionaryFrom(_ order: Order) -> [String : Any] {
var allArticleIds: [String] = []
for article in order.orderItems {
allArticleIds.append(article.id)
}
return NSDictionary(objects: [order.id,
order.customerId,
allArticleIds,
order.amount,
order.customerName,
order.isCompleted
],
forKeys: [kID as NSCopying,
kCUSTOMERID as NSCopying,
kARTICLEIDS as NSCopying,
kAMOUNT as NSCopying,
kCUSTOMERNAME as NSCopying,
kISCOMPLETED as NSCopying
]) as! [String : Any]
}
| true
|
dde07d260a89ce40a78b4389f7d492abad4b7c49
|
Swift
|
miolabs/MIOFramework
|
/MIOSwiftTranspiler/test/local/generics/ambiguous-binary.swift
|
UTF-8
| 400
| 3.4375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
protocol Divisible {
static func /(lhs: Self, rhs: Self) -> String
}
class A: Divisible {
static func /(lhs: A, rhs: A) -> String {
return "a"
}
}
class B: Divisible {
static func /(lhs: B, rhs: B) -> String {
return "b"
}
}
func printBinary<T: Divisible>(_ lhs: T, _ rhs: T) {
print(lhs / rhs)
}
let a1 = A(), a2 = A(), b1 = B(), b2 = B()
printBinary(a1, a2)
printBinary(b1, b2)
| true
|
eb131778a840c6e154395e67a7b75af360ae98a2
|
Swift
|
Matsepura/SMInternDAO
|
/SMInternDAO/SQLite.swift DAO/Translator/SQLiteSwiftTranslator.swift
|
UTF-8
| 2,350
| 2.59375
| 3
|
[] |
no_license
|
//
// SQLiteSwiftTranslator.swift
// SMInternDAO
//
// Created by Semen Matsepura on 24.02.2018.
// Copyright © 2018 Semen Matsepura. All rights reserved.
//
import Foundation
/// Parent class for `SQLite.swift` translators.
/// Translators fill properties of new/existant entities from entries and other way.
open class SQLiteSwiftTranslator<Model: Entity, DBModel: SQLiteSwiftModel> {
open var entryClassName: String {
return NSStringFromClass(DBModel.self).components(separatedBy: ".").last!
}
required public init() { }
open func fill(_ entity: Model, fromEntry: DBModel) {
fatalError("Abstact method")
}
open func fill(_ entry: DBModel, fromEntity: Model, in context: GRDBModel) {
fatalError("Abstact method")
}
open func fill(_ entry: DBModel, fromEntity: Model) {
fatalError("Abstact method")
}
open func fill(_ entries: inout [DBModel], fromEntities: [Model]) {
var newEntries = [DBModel]()
fromEntities
.map { entity -> (DBModel, Model) in
let entry = entries
.filter { $0.entryId == entity.entityId }
.first
if let entry = entry {
return (entry, entity)
} else {
let entry = DBModel()
newEntries.append(entry)
return (entry, entity)
}
}
.forEach {
self.fill($0.0, fromEntity: $0.1)
}
if fromEntities.count < entries.count {
let entityIds = fromEntities.map { $0.entityId }
let deletedEntriesIndexes = entries
.filter { !entityIds.contains($0.entryId) }
deletedEntriesIndexes.forEach {
if let index = entries.index(of: $0) {
entries.remove(at: index)
}
}
} else {
entries.append(contentsOf: newEntries)
}
}
open func fill(_ entities: inout [Model], fromEntries: Set<DBModel>?) {
entities.removeAll()
fromEntries?.forEach {
let model = Model()
entities.append(model)
self.fill(model, fromEntry: $0)
}
}
}
| true
|
5dbbdf6c44ce0273777b6224d8d824b5dbf75d33
|
Swift
|
dimohamdy/technivance
|
/technivance/Model/Competitions/Competition.swift
|
UTF-8
| 2,849
| 2.53125
| 3
|
[] |
no_license
|
//
// CompetitionsResult.swift
//
// Create by Ahmed Tawfik on 22/11/2017
// Copyright © 2017. All rights reserved.
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
import ObjectMapper
class Competition : NSObject, NSCoding, Mappable{
var links : CompetitionLink?
var caption : String?
var currentMatchday : Int?
var id : Int?
var lastUpdated : String?
var league : String?
var numberOfGames : Int?
var numberOfMatchdays : Int?
var numberOfTeams : Int?
var year : String?
class func newInstance(map: Map) -> Mappable?{
return Competition()
}
required init?(map: Map){}
private override init(){}
func mapping(map: Map)
{
links <- map["_links"]
caption <- map["caption"]
currentMatchday <- map["currentMatchday"]
id <- map["id"]
lastUpdated <- map["lastUpdated"]
league <- map["league"]
numberOfGames <- map["numberOfGames"]
numberOfMatchdays <- map["numberOfMatchdays"]
numberOfTeams <- map["numberOfTeams"]
year <- map["year"]
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
@objc required init(coder aDecoder: NSCoder)
{
links = aDecoder.decodeObject(forKey: "_links") as? CompetitionLink
caption = aDecoder.decodeObject(forKey: "caption") as? String
currentMatchday = aDecoder.decodeObject(forKey: "currentMatchday") as? Int
id = aDecoder.decodeObject(forKey: "id") as? Int
lastUpdated = aDecoder.decodeObject(forKey: "lastUpdated") as? String
league = aDecoder.decodeObject(forKey: "league") as? String
numberOfGames = aDecoder.decodeObject(forKey: "numberOfGames") as? Int
numberOfMatchdays = aDecoder.decodeObject(forKey: "numberOfMatchdays") as? Int
numberOfTeams = aDecoder.decodeObject(forKey: "numberOfTeams") as? Int
year = aDecoder.decodeObject(forKey: "year") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
@objc func encode(with aCoder: NSCoder)
{
if links != nil{
aCoder.encode(links, forKey: "_links")
}
if caption != nil{
aCoder.encode(caption, forKey: "caption")
}
if currentMatchday != nil{
aCoder.encode(currentMatchday, forKey: "currentMatchday")
}
if id != nil{
aCoder.encode(id, forKey: "id")
}
if lastUpdated != nil{
aCoder.encode(lastUpdated, forKey: "lastUpdated")
}
if league != nil{
aCoder.encode(league, forKey: "league")
}
if numberOfGames != nil{
aCoder.encode(numberOfGames, forKey: "numberOfGames")
}
if numberOfMatchdays != nil{
aCoder.encode(numberOfMatchdays, forKey: "numberOfMatchdays")
}
if numberOfTeams != nil{
aCoder.encode(numberOfTeams, forKey: "numberOfTeams")
}
if year != nil{
aCoder.encode(year, forKey: "year")
}
}
}
| true
|
90052720442a5c51a29a6772315564b011d5b074
|
Swift
|
EmpireAppDesignz/MailComposer
|
/EmailComposer/EmailComposer/ViewController.swift
|
UTF-8
| 2,694
| 2.84375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// EmailComposer
//
// Created by Eric Rosas on 11/27/18.
// Copyright © 2018 Eric Rosas. All rights reserved.
//
import UIKit
//https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontroller
//Framework required to add mail form
import MessageUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//IBAction to open standard email interface
@IBAction func emailButtonDidTouch(_ sender: UIButton) {
//The mail composition interface
//Use your own email address & subject
let receipients = ["Eric@empireappdesignz.com"]
let subject = "Your App Name"
let messageBody = ""
let configuredMailComposeViewController = configureMailComposeViewController(recepients: receipients, subject: subject, messageBody: messageBody)
//Checking the availability of mail services
if canSendMail() {
self.present(configuredMailComposeViewController, animated: true, completion: nil)
} else {
showSendMailErrorAlert()
}
}
}
//MFMailComposeViewController Delegate
extension ViewController: MFMailComposeViewControllerDelegate {
//Configuring and presenting the composition interface
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
// Dismiss the mail compose view controller.
controller.dismiss(animated: true, completion: nil)
}
func canSendMail() -> Bool {
return MFMailComposeViewController.canSendMail()
}
func configureMailComposeViewController(recepients: [String], subject: String, messageBody: String) -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(recepients)
mailComposerVC.setSubject(subject)
mailComposerVC.setMessageBody(messageBody, isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
sendMailErrorAlert.addAction(cancelAction)
present(sendMailErrorAlert, animated: true, completion: nil)
}
}
| true
|
06f2e58256b13df2450b713735b06a7a78ac2ad2
|
Swift
|
maizer999/Caravan.iOS
|
/AdForest/Models/AdPost/AdPostValue.swift
|
UTF-8
| 1,839
| 3
| 3
|
[] |
no_license
|
//
// AdPostValue.swift
// AdForest
//
// Created by apple on 4/25/18.
// Copyright © 2018 apple. All rights reserved.
//
import Foundation
struct AdPostValue {
var hasSub : Bool!
var hasTemplate : Bool!
var id : String!
var isShow : Bool!
var name : String!
var isChecked : Bool!
var tempIsSelected = false
var isBid : Bool!
var isPay : Bool!
var isImg : Bool!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String:Any]) {
hasSub = dictionary["has_sub"] as? Bool
hasTemplate = dictionary["has_template"] as? Bool
id = dictionary["id"] as? String
isShow = dictionary["is_show"] as? Bool
name = dictionary["name"] as? String
isChecked = dictionary["is_checked"] as? Bool
isBid = dictionary["is_bidding"] as? Bool
isPay = dictionary["can_post"] as? Bool
isImg = dictionary["is_bidding"] as? Bool
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if hasSub != nil{
dictionary["has_sub"] = hasSub
}
if hasTemplate != nil{
dictionary["has_template"] = hasTemplate
}
if id != nil{
dictionary["id"] = id
}
if isShow != nil{
dictionary["is_show"] = isShow
}
if name != nil{
dictionary["name"] = name
}
if isChecked != nil{
dictionary["is_checked"] = isChecked
}
return dictionary
}
}
| true
|
32f243e7fe1388682a9b45942af4f5d8804c62e2
|
Swift
|
faguilhermo/RemoteChallenge
|
/MultiTimer/MultiTimer/View/ContentView.swift
|
UTF-8
| 1,908
| 2.875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// MultiTimer
//
// Created by Fabrício Guilhermo on 18/05/20.
// Copyright © 2020 Fabrício Guilhermo. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var timers: [TimerModel] = []
@State var isAddNewTimerPresented = false
// @State private var selection: Set<TimerModel> = []
var body: some View {
ZStack {
Color("Main-Color")
.edgesIgnoringSafeArea(.all)
VStack(alignment: .trailing) {
Button(action: {
self.isAddNewTimerPresented.toggle()
}) {
Image(uiImage: #imageLiteral(resourceName: "add"))
.foregroundColor(Color("Secondary-Color"))
.padding([.trailing, .top])
}.sheet(isPresented: $isAddNewTimerPresented, content: {
AddNewTimerView(hour: 0, minute: 0, second: 0, addTimer: { timer in
self.timers.append(timer)
})
})
List {
ForEach(timers, id: \.id) { timer in
ListCell(timer: timer, didDelete: { _ in
self.timers.removeAll(where: {$0.id == timer.id})
}, totalTime: timer.totalTime, repeatTimer: timer.repeatTimer)
// .onTapGesture { self.selectDeselect(timer) }
}
}
}
if timers.count == 0 {
Text("Toque no \"+\" e adicione um novo timer")
.modifier(TextCustomModifier(fontType: .addNewTimerMessage))
}
}
}
// private func selectDeselect(_ timer: TimerModel) {
// if selection.contains(timer) {
// selection.remove(timer)
// } else {
// selection.insert(timer)
// }
// }
}
| true
|
a51171e5a140a77593186bf27b0579082f0ec046
|
Swift
|
st-small/Alarmation
|
/Alarmation/AppDelegate.swift
|
UTF-8
| 1,353
| 2.53125
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// Alarmation
//
// Created by Stanly Shiyanovskiy on 06.10.2020.
//
import UIKit
import UserNotifications
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
if let navController = window?.rootViewController as? UINavigationController {
if let viewController = navController.viewControllers[0] as? ViewController {
center.delegate = viewController
}
}
let show = UNNotificationAction(identifier: "show", title: "Show Group", options: .foreground)
let destroy = UNNotificationAction(identifier: "destroy", title: "Destroy Group", options: [.destructive, .authenticationRequired])
let rename = UNTextInputNotificationAction(identifier: "rename", title: "Rename Group", options: [], textInputButtonTitle: "Rename", textInputPlaceholder: "Type the new name here")
let category = UNNotificationCategory(identifier: "alarm", actions: [show, rename, destroy], intentIdentifiers: [], options: [.customDismissAction])
center.setNotificationCategories([category])
return true
}
}
| true
|
e2ecc9e53f0a919798408e449ebae399087c9bc3
|
Swift
|
bschmalb/praxisProjekt
|
/iosapp/iosapp/Profil/ProfilData.swift
|
UTF-8
| 15,993
| 2.609375
| 3
|
[] |
no_license
|
//
// ProfilData.swift
// iosapp
//
// Created by Bastian Schmalbach on 23.09.20.
// Copyright © 2020 Bastian Schmalbach. All rights reserved.
//
import SwiftUI
struct ProfilData: View {
@State var id = UserDefaults.standard.string(forKey: "id")
@Environment(\.presentationMode) var mode: Binding<PresentationMode>
@ObservedObject private var keyboard = KeyboardResponder()
@State var firstResponder: Bool? = false
@State var optionSelected: Int = 1
@State var user: User = User(_id: "", phoneId: "", level: 2, checkedTipps: [], savedTipps: [], savedFacts: [], log: [])
@State var posting: Bool = false
@EnvironmentObject var user2: UserObserv
@EnvironmentObject var myUrl: ApiUrl
@State var name: String = UserDefaults.standard.string(forKey: "userName") ?? "User123"
@State var age: String = ""
@State var gender: String = ""
@State var hideInfo: Bool = UserDefaults.standard.bool(forKey: "hideInfo")
@State var ages: [String] = ["12-17", "18-25", "26-35", "36-50", "51-70", "71+"]
@State var genders: [String] = ["Männlich", "Weiblich", "Divers"]
@State var isSelected: [Bool] = [false, false, false, false, false, false]
@State var isSelectedGender: [Bool] = [false, false, false]
@Binding var isChanged: Bool
var screen = UIScreen.main.bounds
var body: some View {
let binding = Binding<String>(get: {
name
}, set: {
name = $0
UserDefaults.standard.set(name, forKey: "userName")
if (user.name != $0){
self.isChanged = true
}
})
return ZStack {
Color("background")
.edgesIgnoringSafeArea(.all)
VStack{
Button(action: {
self.mode.wrappedValue.dismiss()
impact(style: .medium)
}) {
HStack (spacing: 10){
Image(systemName: "arrow.left")
.font(.system(size: screen.width < 500 ? screen.width * 0.040 : 18, weight: .medium))
.foregroundColor(Color("black"))
Text("Deine Daten")
.font(.system(size: screen.width < 500 ? screen.width * 0.040 : 18, weight: .medium))
.foregroundColor(Color("black"))
Spacer()
}
.padding(.leading, 20)
.padding(.top, 15)
}
Spacer()
VStack {
Text("Name:")
.font(.system(size: 16, weight: Font.Weight.medium))
ZStack{
// MultilineTextView2(text: binding, isFirstResponder: $firstResponder, maxLength: 13)
// .frame(height: 40)
CustomTextField2(text: binding, isFirstResponder: $firstResponder, maxLength: 13)
.frame(height: 40)
VStack {
HStack {
Spacer()
Text("\(name.count)/\(13)")
.padding(10)
.font(.system(size: screen.width < 500 ? screen.width * 0.03 : 12))
.opacity(0.5)
}
}.frame(height: 40)
}
.frame(maxWidth: UIScreen.main.bounds.width < 500 ? UIScreen.main.bounds.width - 30 : 450)
.padding(.horizontal)
Spacer()
if ((!(firstResponder ?? true)) && !(keyboard.currentHeight > 100)) {
Text("Alter")
.font(.system(size: 16, weight: Font.Weight.medium))
.onTapGesture(perform: {
self.hideKeyboard()
})
.onAppear(){
getUser()
}
ScrollView (.horizontal, showsIndicators: false) {
HStack {
ForEach(ages.indices, id: \.self) { index in
Button(action: {
self.age = ages[index]
impact(style: .medium)
for (i, _) in isSelected.enumerated() {
isSelected[i] = false
}
self.isSelected[index] = true
if (ages[index] != user.age){
self.isChanged = true
}
}){
Text(ages[index])
.font(.system(size: 14))
.padding(UIScreen.main.bounds.height < 600 ? 10 : 15)
.foregroundColor(Color(isSelected[index] ? "white" : "black"))
.background(Color(isSelected[index] ? "blue" : "background"))
.cornerRadius(15)
}
}
}.padding(.horizontal)
}
.opacity(hideInfo ? 0.5 : 1)
Spacer()
Text("Geschlecht")
.font(.system(size: 16, weight: Font.Weight.medium))
HStack {
ForEach(genders.indices, id: \.self) { index in
Button(action: {
self.gender = genders[index]
impact(style: .medium)
for (i, _) in isSelectedGender.enumerated() {
isSelectedGender[i] = false
}
self.isSelectedGender[index] = true
if (genders[index] != user.gender){
self.isChanged = true
}
}){
Text(genders[index])
.font(.system(size: 14))
.padding(UIScreen.main.bounds.height < 600 ? 10 : 15)
.foregroundColor(Color(isSelectedGender[index] ? "white" : "black"))
.background(Color(isSelectedGender[index] ? "blue" : "background"))
.cornerRadius(15)
}
}
}
.padding(.vertical, 10)
.opacity(hideInfo ? 0.5 : 1)
Spacer()
Toggle("Diese Angaben Online verstecken", isOn: $hideInfo)
.onReceive([self.hideInfo].publisher.first()) { (value) in
UserDefaults.standard.set(value, forKey: "hideInfo")
if (hideInfo != user.hideInfo){
self.isChanged = true
}
}
.font(.footnote)
.padding()
} else {
Image(systemName: "ellipsis")
.frame(width: 40, height: 20)
.background(Color(.black).opacity(0.1))
.cornerRadius(10)
.padding()
.onTapGesture(perform: {
self.firstResponder = false
self.hideKeyboard()
})
}
Group {
Spacer()
if #available(iOS 14, *) {
Button(action: {
self.posting = true
self.isChanged = true
self.firstResponder = false
self.hideKeyboard()
self.firstResponder = false
self.postUserData(name: name, age: age, gender: gender, hideInfo: hideInfo)
}){
HStack (spacing: 15) {
if (posting) {
LottieView(filename: "loadingWhite", loop: true)
.frame(width: 20, height: 20)
.scaleEffect(3)
} else {
Image(systemName: isChanged ? "doc" : "checkmark")
.font(.headline)
.padding(.leading, 5)
}
Text(isChanged ? "Speichern" : "Gespeichert")
.font(.system(size: screen.width < 500 ? screen.width * 0.050 : 18, weight: .medium))
.padding(.trailing, 3)
}
.accentColor(Color("white"))
.padding(UIScreen.main.bounds.height < 600 ? 10 : 15)
.background(Color("blue"))
.cornerRadius(15)
}
.disabled(!isChanged)
} else {
Button(action: {
self.posting = true
self.isChanged = true
self.firstResponder = false
self.hideKeyboard()
self.firstResponder = false
self.postUserData(name: name, age: age, gender: gender, hideInfo: hideInfo)
}){
HStack (spacing: 15) {
if (posting) {
LottieView(filename: "loadingWhite", loop: true)
.frame(width: 20, height: 20)
.scaleEffect(3)
} else {
Image(systemName: isChanged ? "doc" : "checkmark")
.font(.headline)
.padding(.leading, 5)
}
Text(isChanged ? "Speichern" : "Gespeichert")
.font(.system(size: screen.width < 500 ? screen.width * 0.050 : 18, weight: .medium))
.padding(.trailing, 3)
}
.accentColor(Color("white"))
.padding(screen.height < 600 ? 10 : 15)
.background(Color("blue"))
.cornerRadius(15)
}
.padding(.bottom, keyboard.currentHeight)
.disabled(!isChanged)
}
Spacer()
}
.onTapGesture(perform: {
self.firstResponder = false
self.hideKeyboard()
})
}
.accentColor(.primary)
.background(Color("background"))
.animation(.spring())
Spacer()
}
}
.gesture(DragGesture()
.onChanged({ (value) in
if value.translation.width > 40 {
self.mode.wrappedValue.dismiss()
}
})
)
}
func getUser() {
guard let url = URL(string: myUrl.users + (id ?? "")) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
if let data = data {
if let user = try? JSONDecoder().decode(User.self, from: data) {
// we have good data – go back to the main thread
DispatchQueue.main.async {
// update our UI
self.user = user
if let i = self.ages.firstIndex(of: user.age ?? ""){
self.isSelected[i] = true
self.age = user.age ?? ""
}
if let i = self.genders.firstIndex(of: user.gender ?? ""){
self.isSelectedGender[i] = true
self.gender = user.gender ?? ""
}
if (user.hideInfo ?? false){
self.hideInfo = true
}
self.isChanged = false
}
// everything is good, so we can exit
return
}
}
}
.resume()
}
func postUserData(name: String, age: String, gender: String, hideInfo: Bool){
let patchData = UserNameAgeGen(name: name, age: age, gender: gender, hideInfo: hideInfo)
guard let encoded = try? JSONEncoder().encode(patchData) else {
print("Failed to encode order")
return
}
guard let url = URL(string: myUrl.users + (id ?? "")) else { return }
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "PATCH"
request.httpBody = encoded
URLSession.shared.dataTask(with: request) { data, response, error in
}.resume()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.user.name = user2.name
self.user.age = age
self.user.gender = gender
self.user.hideInfo = hideInfo
self.isChanged = false
self.posting = false
self.getUser()
}
}
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
struct ProfilData_Previews: PreviewProvider {
static var previews: some View {
ProfilData(isChanged: .constant(false)).environmentObject(UserObserv())
}
}
| true
|
d7353ec527d7827b8e4c1b10d249d683ade953b1
|
Swift
|
mutawe90/MAFNews
|
/MAFNews/MAFNews/Views/Controllers/BaseViewController.swift
|
UTF-8
| 1,532
| 2.640625
| 3
|
[] |
no_license
|
//
// BaseViewController.swift
// MAFNews
//
// Created by Yousef Mutawe on 7/9/19.
// Copyright © 2019 Motawe. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class BaseViewController: UIViewController , NVActivityIndicatorViewable {
let activityData = ActivityData()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
fileprivate func showAlert(withTitle title: String, message: String, complition: (() -> ())? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Dismiss", style: .cancel) { (_) in
if let complition = complition {
complition()
}
}
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
extension BaseViewController: BaseCommunicationHandlerDelegate {
func showError(message: String, complition: (() -> ())?) {
showAlert(withTitle: "Error", message: message, complition: complition)
}
func showSuccessMessage(message: String, complition: (() -> ())?) {
showAlert(withTitle: "Success", message: message,complition: complition)
}
func addLoadingIndicator() {
NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData)
}
func removeLoadingIndicator() {
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
}
}
| true
|
e471a22e3a4c1c846261967d305c14671042652c
|
Swift
|
fjavaler/CodableDemo
|
/CodableDemo/ViewModels/CodableViewModel.swift
|
UTF-8
| 2,040
| 3.46875
| 3
|
[] |
no_license
|
//
// CodableViewModel.swift
// CodableDemo
//
// Created by Fred Javalera on 6/10/21.
//
import Foundation
class CodableViewModel: ObservableObject {
@Published var customer: CustomerModel? = nil
init() {
getData()
}
func getData() {
guard let data = getJSONData() else { return }
// // Converts data from JSON data to dictionary without using coding keys (not preferred).
// // If all of these let statements succeed...
// if
// let localData = try? JSONSerialization.jsonObject(with: data, options: []),
// let dictionary = localData as? [String:Any],
// let id = dictionary["id"] as? String,
// let name = dictionary["name"] as? String,
// let points = dictionary["points"] as? Int,
// let isPremium = dictionary["isPremium"] as? Bool {
//
// //...then, create a new customer from the variables and store as customer.
// let newCustomer = CustomerModel(id: id, name: name, points: points, isPremium: isPremium)
// customer = newCustomer
//
// }
// Using coding keys (preferred).
do {
self.customer = try JSONDecoder().decode(CustomerModel.self, from: data)
} catch let error {
print("Error decoding. \(error)")
}
}
func getJSONData() -> Data? {
// Manually creating a JSON object without using CodingKeys and Encodable.
// let dictionary: [String:Any] = [
// "id": "12345",
// "name": "Joe",
// "points": 5,
// "isPremium": true
// ]
//
// // Converts dictionary into JSON data
// let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
// With encodable
let customer = CustomerModel(id: "111", name: "Emily", points: 100, isPremium: false)
do {
let jsonData = try JSONEncoder().encode(customer)
return jsonData
} catch let error {
print("Error encoding. \(error)")
}
return Data()
}
}
| true
|
151c936997f8c25b755adfe89d0f25a3937765c8
|
Swift
|
j1george/scituner
|
/SciTuner/Views/PanelView.swift
|
UTF-8
| 2,620
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// PanelView.swift
// oscituner
//
// Created by Denis Kreshikhin on 13.12.14.
// Copyright (c) 2014 Denis Kreshikhin. All rights reserved.
//
import UIKit
class PanelView: UIView {
var notebar: NotebarView?
var stringbar: StringbarView?
var target: UILabel?
var actual: UILabel?
var deviation: UILabel?
var targetFrequency: UILabel?
var actualFrequency: UILabel?
var frequencyDeviation: UILabel?
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
let margin: CGFloat = 10.0;
let half = frame.size.width / 2;
let third = (frame.size.width - 2*margin) / 3;
let step = frame.size.height / 5.0;
target = UILabel(frame: CGRect(x: margin, y: 2, width: third, height: 12))
target!.text = "target frequency"
target!.font = UIFont.systemFont(ofSize: 10)
target!.textAlignment = .left
self.addSubview(target!)
actual = UILabel(frame: CGRect(x: margin+third, y: 2, width: third, height: 12))
actual!.text = "actual frequency"
actual!.font = UIFont.systemFont(ofSize: 10)
actual!.textAlignment = .center
self.addSubview(actual!)
deviation = UILabel(frame: CGRect(x: margin+2*third, y: 2, width: third, height: 12))
deviation!.text = "deviation"
deviation!.font = UIFont.systemFont(ofSize: 10)
deviation!.textAlignment = .right
self.addSubview(deviation!)
targetFrequency = UILabel(frame: CGRect(x: margin, y: 14, width: third, height: 20))
targetFrequency!.text = "440Hz"
targetFrequency!.textAlignment = .left
self.addSubview(targetFrequency!)
actualFrequency = UILabel(frame: CGRect(x: margin+third, y: 14, width: third, height: 20))
actualFrequency!.text = "440Hz"
actualFrequency!.textAlignment = .center
self.addSubview(actualFrequency!)
frequencyDeviation = UILabel(frame: CGRect(x: margin+2*third, y: 14, width: third, height: 20))
frequencyDeviation!.text = "0c"
frequencyDeviation!.textAlignment = .right
self.addSubview(frequencyDeviation!)
notebar = NotebarView(frame: CGRect(x: 0, y: step, width: half*2, height: 40))
stringbar = StringbarView(frame: CGRect(x: 0, y: 2*step, width: half*2, height: 40))
self.addSubview(notebar!)
self.addSubview(stringbar!)
}
}
| true
|
48bb4e3f549f224ddba6317eb4ff189393c6e356
|
Swift
|
w11p3333/WeiDo
|
/WeiDo/Classes/Home-首页/WDNews.swift
|
UTF-8
| 1,455
| 2.671875
| 3
|
[] |
no_license
|
//
// WDNews.swift
// WeiDo
//
// Created by 卢良潇 on 16/3/11.
// Copyright © 2016年 卢良潇. All rights reserved.
//
import UIKit
class WDNews: NSObject {
/// 标题
var title:String?
var picUrl:String?
var url:String?
var ctime:String?
var newsDescription:String?
init(dictionary: [String: AnyObject]) {
title = dictionary["title"] as? String
picUrl = dictionary["picUrl"] as? String
url = dictionary["url"] as? String
ctime = dictionary["ctime"] as? String
newsDescription = dictionary["description"] as? String
}
static func LoadNews(results: [[String : AnyObject]]) -> [WDNews] {
var news = [WDNews]()
for result in results {
news.append(WDNews(dictionary: result))
}
return news
}
class func loadNewsData(path:String,finished:(models:[WDNews]?,error:NSError?) -> ())
{
let path = "http://api.huceo.com/" + path + "/"
let newsParams = ["key":"28874a32bce9a4b984c57c3538e68809","num":20]
NetworkTools.shareNetworkTools().GET(path, parameters: newsParams, success: { (_, JSON) in
let model = LoadNews(JSON!["newslist"] as! [[String:AnyObject]])
finished(models: model, error: nil)
}) { (_, error) in
finished(models: nil, error: error)
}
}
}
| true
|
07797ab2d0e7bf2c02c0c545fa4be76bc817e200
|
Swift
|
Lerist/HighlightTextView
|
/HighlightTextView/HighlightTextView.swift
|
UTF-8
| 1,340
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// HighlightTextView.swift
// HighlightTextView
//
// Created by KazukiYusa on 2016/10/10.
// Copyright © 2016年 KazukiYusa. All rights reserved.
//
import UIKit
open class HighlightTextView: UITextView {
open var characterLimit: Int = 100
open var overLimitBackgroundColor: UIColor = #colorLiteral(red: 1, green: 0.4932718873, blue: 0.4739984274, alpha: 1)
open override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default
.addObserver(self,
selector: #selector(self.didChangeTextView),
name: NSNotification.Name.UITextViewTextDidChange,
object: self)
}
private dynamic func didChangeTextView() {
if text.characters.count < characterLimit {
return
}
if markedTextRange != nil {
return
}
let attributes = NSMutableAttributedString(attributedString: attributedText)
attributes.addAttributes([NSBackgroundColorAttributeName: overLimitBackgroundColor],
range: NSRange(location: characterLimit,
length: text.characters.count - characterLimit))
attributedText = attributes
}
}
| true
|
2cdfdad1b5f11c0c36f9b58bf217360ea23909cc
|
Swift
|
skabbass1/MyWOD
|
/Tests/MyWODTests/ParserTests.swift
|
UTF-8
| 803
| 2.671875
| 3
|
[] |
no_license
|
import Foundation
import Quick
import Nimble
import MyWODCore
class ParserSpec: QuickSpec {
override func spec() {
it("Extracts WOD details from HTML page correctly") {
var fileHandle = FileHandle(forReadingAtPath: "Tests/MyWODTests/TestData.html")
let contents = String(data: fileHandle!.readDataToEndOfFile(), encoding: .utf8)
fileHandle?.closeFile()
fileHandle = FileHandle(forReadingAtPath: "Tests/MyWODTests/ExpectedParserOutput.txt")
let expected = String(data: fileHandle!.readDataToEndOfFile(), encoding: .utf8)
fileHandle?.closeFile()
let got = Parser.extractWOD(rawHtml: contents!)
expect(got).to(equal(expected))
}
}
}
| true
|
b1ceb04ea187d0499bb1acc9478de987eb7a0754
|
Swift
|
Pavel71/Otus_Swift_HomeWorks
|
/HomeWork_02/HomeWork_02/ViewLayer/MainScreen/ViewModel/WithPublisher/WeatherVMWithPublishers.swift
|
UTF-8
| 2,527
| 2.9375
| 3
|
[] |
no_license
|
//
// WeatherVMWithPublishers.swift
// HomeWork_02
//
// Created by Павел Мишагин on 30.12.2019.
// Copyright © 2019 Павел Мишагин. All rights reserved.
//
import Combine
import SwiftUI
final class WeatherVMWithPublishers: ObservableObject {
@Published var isactivateAnimation : Bool = false
@Published var isLoaded : Bool = false
@Published var selectedCity : Int = 0
var selectedCityName : String {
print("Computed Favorit CityName , \(favoritsCity[selectedCity])")
return favoritsCity[selectedCity]
}
var cityWeatherModel : WeatherModel = WeatherModel(conditionId: 800, cityName: "Ошибка API", temperature: 0)
var weatherApi = WeatherAPi.shared
private var cancellableSet : Set <AnyCancellable> = []
// ScrollView
// ВОзможно стоит переписать свою ViewModel
var allCity = ["Barcelona","Dubai","New York","Los Angeles"]
@Published var loadingNewCityies: Bool = false {
didSet {
if oldValue == false && loadingNewCityies == true {
self.addNewCities()
}
}
}
@Published var favoritsCity = ["Tula","London","Moscow","Paris","Berlin"]
init() {
// ScrollView Selected New City
$selectedCity.flatMap { (selectedIndex) -> AnyPublisher<WeatherModel, Never> in
self.isactivateAnimation = false
self.isLoaded = false
return self.weatherApi.fecthCityWeather(city: self.favoritsCity[selectedIndex])
.replaceError(with: WeatherModel(conditionId: 800, cityName: "Ошибка API", temperature: 0))
.eraseToAnyPublisher()
}.sink(receiveValue: { (weatherModel) in
self.cityWeatherModel = weatherModel
self.isLoaded = true
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(60)) {
self.isactivateAnimation = true
}
})
.store(in: &cancellableSet)
}
// Метод имитирует добавление новых городов в нашу коллекцию!
func addNewCities() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
self.loadingNewCityies = false
guard let lastCity = self.allCity.last else {return}
self.allCity = self.allCity.dropLast()
self.favoritsCity.append(lastCity)
}
}
deinit {
for cancel in cancellableSet {
cancel.cancel()
}
}
}
| true
|
b8a188b4d1280131c700125b43e24df014db75f8
|
Swift
|
trinhson97/ScrollViewZoom-master
|
/ScrollViewZoom/ViewController.swift
|
UTF-8
| 1,794
| 2.75
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ScrollViewZoom
//
// Created by tham gia huy on 5/22/18.
// Copyright © 2018 tham gia huy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func handlePinch(recognizer: UIPinchGestureRecognizer) {
if let view = recognizer.view {
view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
recognizer.scale = 1
}
}
fileprivate func updateMinZoomScaleForSize(_ size: CGSize) {
let widthScale = size.width / imageView.bounds.width
let heightScale = size.height / imageView.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
| true
|
f933dc1587ffb42d79518b8ab9580f5718c46cac
|
Swift
|
skrew/UIKitPlus
|
/Classes/Extensions/UIColor+Dynamic.swift
|
UTF-8
| 544
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
public func /(lhs: UIColor, rhs: UIColor) -> UIColor {
if #available(iOS 13.0, *) {
return UIColor { $0.userInterfaceStyle == .dark ? rhs : lhs }
} else {
return lhs
}
}
public func /(lhs: CGColor, rhs: CGColor) -> CGColor {
if #available(iOS 13.0, *) {
//let isDark = UIScreen.main.traitCollection.userInterfaceStyle == .dark
//return isDark ? rhs : lhs
return UIScreen.main.traitCollection.userInterfaceStyle == .dark ? rhs : lhs
} else {
return lhs
}
}
| true
|
bc00d144aea0e4af0931fdf3c5d8b47784c12ad1
|
Swift
|
AsunaMS/FinanceTracker
|
/FinanceTracker/models/objects.swift
|
UTF-8
| 4,505
| 3.03125
| 3
|
[] |
no_license
|
//
// Invoice.swift
// FinanceTracker
//
// Created by נדב אבנון on 01/02/2021.
//
import UIKit
struct Person {
var firstName:String
var lastName:String
var invoices:[Invoice]
var balance:Int
var income:Int
var expense:Int
mutating func invoiceAdded(invoice:Invoice) {
invoices.append(invoice)
guard let amount = invoice.invoiceAmount else {return}
if invoice.invoiceInOut == .expense {
balance = balance - amount
expense = expense + amount
} else if invoice.invoiceInOut == .income {
balance = balance + amount
income = income + amount
}
}
}
class Invoice {
var invoiceTitle:String?
var invoiceDesc:String?
var invoiceDate:Date?
var invoiceType:invoiceType?
var invoiceAmount:Int?
var invoiceInOut:invoiceInOut?
init(invoiceTitle:String?,invoiceDesc:String?,invoiceInOut:invoiceInOut?, invoiceType:invoiceType?,invoiceAmount:Int?,invoiceDate:Date?) {
self.invoiceTitle = invoiceTitle
self.invoiceDesc = invoiceDesc
self.invoiceType = invoiceType
self.invoiceAmount = invoiceAmount
self.invoiceDate = invoiceDate
self.invoiceInOut = invoiceInOut
}
convenience init(invoiceType:invoiceType) {
self.init(invoiceTitle: nil, invoiceDesc: nil, invoiceInOut: nil, invoiceType: invoiceType, invoiceAmount: nil, invoiceDate: nil)
}
func setInvoiceAmount(invoiceAmount:Int,invoiceInOut:invoiceInOut){
self.invoiceAmount = invoiceAmount
self.invoiceInOut = invoiceInOut
}
}
enum invoiceInOut {
case expense
case income
var textColor:UIColor {
switch self {
case .expense:
return #colorLiteral(red: 0.6075268817, green: 0.08433429636, blue: 0.1327555175, alpha: 1)
case .income:
return #colorLiteral(red: 0.1960784346, green: 0.3411764801, blue: 0.1019607857, alpha: 1)
}
}
var textSign:String {
switch self {
case .expense:
return "-"
case .income:
return "+"
}
}
}
enum invoiceType {
case flight
case clothing
case salary
case groceries
case rent
case other
public static let invoiceImageBorderColor:CGColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
public static let invoiceImageBorderWidth:CGFloat = 1.0
public static let invoiceImageBgOpacity:CGFloat = 0.1
public static let invoiceImageBorderCornerRadius:CGFloat = 30.0
var invoiceTypeName:String {
switch self {
case .flight:
return "Flight"
case .clothing:
return "Clothing"
case .groceries:
return "Groceries"
case .salary:
return "Salary"
case .rent:
return "Rent"
case .other:
return "Other"
}
}
var invoiceIcon:UIImage? {
switch self {
case .flight:
return #imageLiteral(resourceName: "plane")
case .clothing:
return #imageLiteral(resourceName: "clothing")
case .salary:
return #imageLiteral(resourceName: "salary")
case .groceries:
return #imageLiteral(resourceName: "groceries")
case .rent:
return #imageLiteral(resourceName: "rent")
case .other:
return #imageLiteral(resourceName: "other")
}
}
var invoiceImageBgColor:UIColor? {
let opacity = invoiceType.invoiceImageBgOpacity
switch self {
case .flight:
return #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1).withAlphaComponent(opacity)
case .clothing:
return #colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1).withAlphaComponent(opacity)
case .salary:
return #colorLiteral(red: 0.1294117719, green: 0.2156862766, blue: 0.06666667014, alpha: 1).withAlphaComponent(opacity)
case .groceries:
return #colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1).withAlphaComponent(opacity)
case .rent:
return #colorLiteral(red: 0.6075268817, green: 0.08433429636, blue: 0.1327555175, alpha: 1).withAlphaComponent(opacity)
case .other:
return #colorLiteral(red: 0.3176470697, green: 0.07450980693, blue: 0.02745098062, alpha: 1).withAlphaComponent(opacity)
}
}
}
| true
|
b643a52ba7a92172ce482b540689d354de22cc59
|
Swift
|
PabloAlejandro/Weather
|
/Weather/Classes/History/History.swift
|
UTF-8
| 1,600
| 3.140625
| 3
|
[] |
no_license
|
//
// History.swift
// Weather
//
// Created by Pau on 26/10/2016.
// Copyright © 2016 Pau. All rights reserved.
//
import Foundation
private let key: String = "last_searches"
class History {
private class func setLastSearches(lastSearches: [String]?) {
let defaults: UserDefaults = UserDefaults.standard
defaults.set(lastSearches, forKey: key)
defaults.synchronize()
}
class func addSearch(search: String) {
var lastSearches = History.lastSearches()
if let index = lastSearches.index(of: search) {
lastSearches.remove(at: index)
}
lastSearches.append(search)
History.setLastSearches(lastSearches: lastSearches)
}
class func removeSearch(search: String) {
var lastSearches = History.lastSearches()
if let index = lastSearches.index(of: search) {
lastSearches.remove(at: index)
}
History.setLastSearches(lastSearches: lastSearches)
}
class func clear() {
History.setLastSearches(lastSearches: nil)
}
class func lastSearch() -> String? {
let defaults: UserDefaults = UserDefaults.standard
guard let lastSearches = defaults.object(forKey: key) as? [String] else {
return nil
}
return lastSearches.last
}
class func lastSearches() -> [String] {
let defaults: UserDefaults = UserDefaults.standard
guard let lastSearches = defaults.object(forKey: key) as? [String] else {
return []
}
return lastSearches
}
}
| true
|
9e25aa4eeaa11026d627964e1c3da36b0796f3ce
|
Swift
|
mdogan93/ecies-iOS
|
/ec-encryption/ViewController.swift
|
UTF-8
| 2,877
| 2.765625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ec-encryption
//
// Created by Mehmet Doğan on 14.02.2019.
// Copyright © 2019 Mehmet Doğan. All rights reserved.
//
import UIKit
import Blockstack
import CryptoSwift
//protocol Serializable: Codable {
// func serialize() -> Data?
//}
//
//extension Serializable {
// func serialize() -> Data? {
// let encoder = JSONEncoder()
// return try? encoder.encode(self)
// }
//
//}
//
//extension Data{
// func jsonToString()->String{
// var convertedString:String?
// do {
// let data1 = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
// convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
// print(convertedString) // <-- here is ur string
// return convertedString!
// } catch let myJSONError {
// print(myJSONError)
// }
// return convertedString!
// }
//}
class ViewController: UIViewController {
@IBOutlet weak var txtDecrypted: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func decryption(_ sender: UIButton) {
var testData = dataModel()
testData.ciphertext = "fc5d25c3253585fa601b0076933c3962"
testData.ephemPublicKey = "04d33d0ed1481f6f379fa990ec4759739dd845d611e5550775c6f15bb3be941981d2fdf43905fa6005e5caca2a6b219fb392cda0b461f8c01a98d375b5e00d4537"
testData.iv = "6912821b450859349b9c8e53b59eaee3"
testData.mac = "c4389a8ba97238eec5eb78649740bb7d3c4fb020ef0393872f5a9b9c160bdc29"
let jsonEncoder = JSONEncoder()
let jsonData = try? jsonEncoder.encode(testData)
let json = String(data: jsonData!, encoding: String.Encoding.utf8)
let jsonDecoder = JSONDecoder()
let dtsample = try! jsonDecoder.decode(dataModel.self, from: jsonData!)
let newdata = decryptECIES(cipherObjectJSONString: json!,privateKey: "bfe861192b89df231018d77e8ed4df781f6aec1d3b134a304426c0f89e709e0a" )
txtDecrypted.text = newdata!
}
}
func decryptECIES(cipherObjectJSONString: String, privateKey: String) -> String? {
let jsonDecoder = JSONDecoder()
let jsonData = cipherObjectJSONString.data(using: .utf8)!
let dtsample = try! jsonDecoder.decode(dataModel.self, from: jsonData)
let out = Blockstack.shared.decryptContent(content: cipherObjectJSONString, privateKey: privateKey)
return out?.plainText
}
struct dataModel : Codable{
var ephemPublicKey:String?
var iv:String?
var mac:String?
var ciphertext:String?
private enum CodingKeys: String, CodingKey {
case ephemPublicKey
case iv
case mac
case ciphertext
}
}
| true
|
1a8f3e46bd599d6023238d88f30f1f04ef27de76
|
Swift
|
MatheusVaccaro/WWDC2018
|
/Tower of Hanoi.playgroundbook/Contents/Chapters/Chapter1.playgroundchapter/Pages/Page2.playgroundpage/Contents.swift
|
UTF-8
| 2,666
| 3.796875
| 4
|
[] |
no_license
|
//#-hidden-code
import PlaygroundSupport
let page = PlaygroundPage.current
let proxy = page.liveView as? PlaygroundRemoteLiveViewProxy
var numberOfRods = 3
var numberOfDisks = 3
func updateTower() {
let dict = ["title" : PlaygroundValue.string("towerUpdate"),
"nRods" : PlaygroundValue.integer(numberOfRods),
"nDisks": PlaygroundValue.integer(numberOfDisks)]
proxy?.send(PlaygroundValue.dictionary(dict))
}
func moveTopDisk(fromRod sourceRod: Int, toRod targetRod: Int) {
let dict = ["title" : PlaygroundValue.string("moves"),
"sourceRod" : PlaygroundValue.integer(sourceRod),
"targetRod": PlaygroundValue.integer(targetRod)]
proxy?.send(PlaygroundValue.dictionary(dict))
}
func executeMoves() {
let string = PlaygroundValue.string("executeMoves")
proxy?.send(string)
}
func clearMovementQueue() {
let string = PlaygroundValue.string("clearMovementQueue")
proxy?.send(string)
}
clearMovementQueue()
//#-end-hidden-code
/*:
# Play Time!
Congratulations! 🎉 Now that you know everything about the Tower of Hanoi, it's time to play!
You can use this page to create your own versions of the puzzle with any number of rods and disk stack sizes you want!
- Important:
The greater the number of disks in a stack, the harder the puzzle gets.
\
The greater the number of rods, the easier the puzzle gets.
Just remember, if you build the tower with 3 rods, the minimal number of moves required to solve it is given by the equation
* Callout(Equation):
`Minimal Number of Moves = 2ˆ(Number of Disks) - 1`
So... considering that, if you set the number of disks in the stack to 7, you'll be making at least 127 moves...
**Have Fun!** 😁
Ahh! And one more thing! If you are wondering what are the moves to solve the Tower of Hanoi, I have compiled some solutions for you in the **Solutions Chapter**. 😉
*/
//#-code-completion(everything, hide)
// The number of rods the puzzle will have.
// Choose a number greater than 3, or the puzzle won't be solvable.
numberOfRods = /*#-editable-code*/3/*#-end-editable-code*/
// Determines how many disks will be stacked on the first rod.
// For best results, choose a number between 3 and 7.
numberOfDisks = /*#-editable-code*/3/*#-end-editable-code*/
//#-code-completion(description, show, "moveTopDisk(fromRod: Int, toRod: Int)")
// Here you can type the commands you want the tower to make, just remember that you can interact with the puzzle by touching the rods too.
//#-editable-code Tap to enter code
//#-end-editable-code
//#-hidden-code
updateTower()
executeMoves()
//#-end-hidden-code
| true
|
ff42a6b0db9a2f1504e0ddf72fec30952f09a1cf
|
Swift
|
changdiqing/RichtextEditor
|
/journal/Views/ColorKeyboard.swift
|
UTF-8
| 2,518
| 2.765625
| 3
|
[] |
no_license
|
//
// KeyBoard.swift
// Custom Keyboard
//
// Created by Diqing Chang on 08.04.18.
// Copyright © 2018 Diqing Chang. All rights reserved.
//
import UIKit
class ColorKeyboard: UIView,UICollectionViewDataSource{
fileprivate let colorList = defaultColors.defaultColorList
// This variable will be set as the view controller so that
// the keyboard can send messages to the view controller.
weak var delegate: KeyboardDelegate?
@IBOutlet weak var colorKeyboardCollectionView: UICollectionView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeSubviews()
}
func initializeSubviews() {
let xibFileName = "Keyboard" // xib extention not included
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)![0] as! UIView
self.addSubview(view)
view.frame = self.bounds
self.colorKeyboardCollectionView.dataSource = self
self.colorKeyboardCollectionView.delegate = self
self.colorKeyboardCollectionView.register(UINib(nibName: "ColorKeyboardCell", bundle: nil), forCellWithReuseIdentifier: "colorKeyboardCell")
}
}
extension ColorKeyboard: UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
// MARK:- UICollectionViewDataSource Methods
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colorList.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedColor: UIColor = colorList[indexPath.item]
delegate?.keyWasTapped(color: selectedColor)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "colorKeyboardCell", for: indexPath) as! ColorKeyboardCell
let color = colorList[indexPath.row]
cell.backgroundColor = color
return cell
}
//MARK:- UICollectionViewDelegate Methods
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 50, height: 50);
}
}
| true
|
f8323fa6911c5951e865478a07f8861e3fd1ade8
|
Swift
|
puffinsupply/TransitioningKit
|
/TransitioningKit/PSPanGestureInteractionController.swift
|
UTF-8
| 7,730
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Adam Michela, The Puffin Supply Project
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@objc public protocol PSPanGestureInteractionControllerDelegate {
optional func handlePanGestureBeganLeft(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
optional func handlePanGestureBeganRight(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
optional func handlePanGestureBeganUp(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
optional func handlePanGestureBeganDown(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
optional func handlePanGestureEndedLeft(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
optional func handlePanGestureEndedRight(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
optional func handlePanGestureEndedUp(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
optional func handlePanGestureEndedDown(gestureRecognizer gestureRecognizer: UIPanGestureRecognizer, viewController: UIViewController, interactionController: UIPercentDrivenInteractiveTransition)
}
public class PSPanGestureInteractionController: UIPercentDrivenInteractiveTransition {
var viewController: UIViewController!
var delegate: PSPanGestureInteractionControllerDelegate?
public init(viewController: UIViewController, delegate: PSPanGestureInteractionControllerDelegate?) {
super.init()
self.viewController = viewController
self.delegate = delegate
addPanGestureRecognizer()
}
// MARK: Public
public func handlePanGesture(gestureRecognizer: UIPanGestureRecognizer) {
switch gestureRecognizer.state {
case .Began: handlePanGestureBegan(gestureRecognizer)
case .Changed: handlePanGestureChanged(gestureRecognizer)
case .Ended: handlePanGestureEnded(gestureRecognizer)
default: handlePanGestureDefault(gestureRecognizer)
}
}
// MARK: Private
private var trackingDirection: Direction?
private enum Orientation: Int {
case Horizontal = 0
case Vertical = 1
}
private enum Direction: Int {
case Left = 0
case Right = 1
case Up = 2
case Down = 3
var orientation: Orientation {
switch self {
case .Left: return .Horizontal
case .Right: return .Horizontal
case .Up: return .Vertical
case .Down: return .Vertical
}
}
}
private func addPanGestureRecognizer() {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
viewController.view.addGestureRecognizer(panGestureRecognizer)
}
private func handlePanGestureBegan(gestureRecognizer: UIPanGestureRecognizer) {
switch panGestureDirection(gestureRecognizer) {
case .Left:
trackingDirection = .Left
delegate?.handlePanGestureBeganLeft?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
case .Right:
trackingDirection = .Right
delegate?.handlePanGestureBeganRight?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
case .Up:
trackingDirection = .Up
delegate?.handlePanGestureBeganUp?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
case .Down:
trackingDirection = .Down
delegate?.handlePanGestureBeganDown?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
}
}
private func handlePanGestureChanged(gestureRecognizer: UIPanGestureRecognizer) {
if !trackingDirectionDidChange(gestureRecognizer) {
let translation = gestureRecognizer.translationInView(viewController.view)
var percentComplete: CGFloat!
switch trackingDirection!.orientation {
case .Horizontal: percentComplete = fabs(translation.x / CGRectGetWidth(viewController.view.bounds))
case .Vertical: percentComplete = fabs(translation.y / CGRectGetHeight(viewController.view.bounds))
}
updateInteractiveTransition(percentComplete)
}
}
private func handlePanGestureEnded(gestureRecognizer: UIPanGestureRecognizer) {
switch trackingDirection! {
case .Left:
delegate?.handlePanGestureEndedLeft?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
case .Right:
delegate?.handlePanGestureEndedRight?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
case .Up:
delegate?.handlePanGestureEndedUp?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
case .Down:
delegate?.handlePanGestureEndedDown?(gestureRecognizer: gestureRecognizer, viewController: viewController, interactionController: self)
}
}
private func handlePanGestureDefault(gestureRecognizer: UIPanGestureRecognizer) {
cancelInteractiveTransition()
}
private func panGestureDirection(gestureRecognizer: UIPanGestureRecognizer) -> Direction {
let velocity = gestureRecognizer.velocityInView(viewController.view)
switch panGestureOrientation(gestureRecognizer) {
case .Horizontal: return (velocity.x < 0) ? .Left : .Right
case .Vertical: return (velocity.y < 0) ? .Up : .Down
}
}
private func panGestureOrientation(gestureRecognizer: UIPanGestureRecognizer) -> Orientation {
let velocity = gestureRecognizer.velocityInView(viewController.view)
return (fabs(velocity.x) > fabs(velocity.y)) ? .Horizontal : .Vertical
}
private func trackingDirectionDidChange(gestureRecognizer: UIPanGestureRecognizer) -> Bool {
let translation = gestureRecognizer.translationInView(viewController.view)
switch trackingDirection! {
case .Left: return (translation.x > 0)
case .Right: return (translation.x < 0)
case .Up: return (translation.y > 0)
case .Down: return (translation.y < 0)
}
}
}
| true
|
a296dc400bd592ddb931f5ecc7fbef682dd35178
|
Swift
|
arkdan/AdChat
|
/AdChat/ViewModel/UserListCellViewModel.swift
|
UTF-8
| 1,161
| 2.796875
| 3
|
[] |
no_license
|
//
// UserListCellViewModel.swift
// Contacts
//
// Created by mac on 8/8/17.
// Copyright © 2017 arkdan. All rights reserved.
//
import Foundation
import ReactiveSwift
import Result
protocol UserListCellViewModelInputs {
var loadChatProperty: MutableProperty<Void> { get }
}
protocol UserListCellViewModelOutputs {
var username: String { get }
var userImage: Data { get }
var loadChat: Signal<User, NoError> { get }
}
struct UserListCellViewModel: UserListCellViewModelInputs, UserListCellViewModelOutputs {
let username: String
let userImage: Data
let loadChatProperty: MutableProperty<Void>
var loadChat: Signal<User, NoError>
init(user: User) {
self.username = user.name
self.userImage = user.avatar.imageData
self.loadChatProperty = MutableProperty()
let (signal, observer) = Signal<User, NoError>.pipe()
self.loadChat = signal
self.loadChatProperty.signal.observeValues { _ in
observer.send(value: user)
}
}
var inputs: UserListCellViewModelInputs { return self }
var outputs: UserListCellViewModelOutputs { return self }
}
| true
|
1f2251347bce9061296c57402b05b5644f536c3d
|
Swift
|
BenAfonso/FlowBook-iOS
|
/FlowBook/ChangePasswordViewController.swift
|
UTF-8
| 2,791
| 2.890625
| 3
|
[] |
no_license
|
//
// ResetPasswordViewController.swift
// FlowBook
//
// Created by Benjamin Afonso on 07/02/2017.
// Copyright © 2017 Benjamin Afonso. All rights reserved.
//
import UIKit
class ChangePasswordViewController: UIViewController {
// Textfield
@IBOutlet weak var oldPasswordField: CustomInputPassword!
@IBOutlet weak var newPasswordField: CustomInputPassword!
@IBOutlet weak var repeatPasswordField: CustomInputPassword!
// Buttons
@IBOutlet weak var validateButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
// Labels
@IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
oldPasswordField.styleInputPassword()
newPasswordField.styleInputPassword()
repeatPasswordField.styleInputPassword()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func cancelAction(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func changePasswordAction(_ sender: Any) {
guard let oldPassword = oldPasswordField.text, oldPassword != "" else {
//oldPasswordField.showErrorBorder()
self.displayError(message: "Veuillez renseigner votre ancien mot de passe")
return
}
guard let newPassword = newPasswordField.text, newPassword != "",
AuthenticationService.checkPasswordValid(password: newPassword) else {
self.displayError(message: "Le nouveau mot de passe doit avoir au moins 6 caractères")
return
}
guard let repeatPassword = repeatPasswordField.text, repeatPassword != "",
AuthenticationService.checkPasswords(password1: newPassword, password2: repeatPassword) else {
print("Invalid repeated password");
self.displayError(message: "Les mots de passe ne sont pas identique")
return
}
if AuthenticationService.checkCredentials(email: (CurrentUser.get()?.email)!, password: oldPassword) {
CurrentUser.get()?.changePassword(toPassword: newPassword)
self.dismiss(animated: true, completion: nil)
} else {
print("Not right password");
self.displayError(message: "L'ancien mot de passe est incorrect")
return
}
}
func displayError(message: String) {
self.errorLabel.isHidden = false
self.errorLabel.text = message
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
fed13689a5880400818b2997ec64675ab01f471d
|
Swift
|
DamianSheldon/SwiftSampleCode
|
/Oxygen/Oxygen/ImageScrollView.swift
|
UTF-8
| 2,655
| 3
| 3
|
[] |
no_license
|
//
// ImageScrollView.swift
// Oxygen
//
// Created by Meiliang Dong on 2018/11/17.
// Copyright © 2018 Meiliang Dong. All rights reserved.
//
import UIKit
open class ImageScrollView: UIScrollView {
private let image: UIImage
private var hasSettedUpTiledImageView = false
private var minmumScale: CGFloat = 1.0
private var imageScale: CGFloat = 1.0
private var frontTiledImageView: TiledImageView!
public init(frame: CGRect, image: UIImage) {
self.image = image
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func layoutSubviews() {
super.layoutSubviews()
if !hasSettedUpTiledImageView {
hasSettedUpTiledImageView = true
var imageRect = CGRect(x: 0, y: 0, width: image.cgImage?.width ?? 1, height: image.cgImage?.height ?? 1)
imageScale = frame.width / imageRect.size.width
minimumZoomScale = 0.75 * imageScale
imageRect.size = CGSize(width: imageRect.size.width * imageScale, height: imageRect.size.height * imageScale)
let scaledImage = ImageHelper.scaledImage(image, factor: imageScale)
frontTiledImageView = TiledImageView(frame: imageRect, image: scaledImage, scale: imageScale)
addSubview(frontTiledImageView)
}
// center the image as it becomes smaller than the size of the screen
let boundsSize = bounds.size
var frameToCenter = frontTiledImageView.frame
// center horizontally
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2.0
}
else {
frameToCenter.origin.x = 0
}
// center vertically
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2.0
}
else {
frameToCenter.origin.y = 0
}
frontTiledImageView.frame = frameToCenter
// to handle the interaction between CATiledLayer and high resolution screens, we need to manually set the
// tiling view's contentScaleFactor to 1.0. (If we omitted this, it would be 2.0 on high resolution screens,
// which would cause the CATiledLayer to ask us for tiles of the wrong scales.)
frontTiledImageView.contentScaleFactor = 1.0;
}
}
| true
|
dc098748206791410f4138f8cb49de693272cd25
|
Swift
|
juanuribeo13/appgate
|
/Appgate/Modules/Home/HomeView.swift
|
UTF-8
| 2,260
| 2.625
| 3
|
[] |
no_license
|
//
// HomeView.swift
// Appgate
//
// Created by Juan Uribe on 15/05/21.
//
import SwiftUI
struct HomeView: View {
// MARK: - Properties
@ObservedObject var viewModel: HomeViewModel
// MARK: - View
var body: some View {
NavigationView {
Form {
Section {
TextField("Username", text: $viewModel.username)
.textContentType(.emailAddress)
.keyboardType(.emailAddress)
SecureField("Password", text: $viewModel.password)
}
.autocapitalization(.none)
.disableAutocorrection(true)
Section {
Button("Create account") {
hideKeyboard()
viewModel.createAccount()
}
Button("Validate account") {
hideKeyboard()
viewModel.validateAccount()
}
if viewModel.isValidated {
NavigationLink(
destination: ValidationAttemptListView(
viewModel: viewModel.validationAttemptsVM)) {
Text("View validation attempts")
}
}
}
.disabled(!viewModel.isValid)
}
.navigationBarTitle("Appgate")
.alert(item: $viewModel.alert) { alert in
Alert(title: Text(alert.title),
message: Text(alert.message),
dismissButton: .default(
Text(alert.dismissText),
action: {
alert.dismissAction?()
}))
}
}
}
// MARK: - Private Functions
private func hideKeyboard() {
UIApplication.shared.sendAction(
#selector(UIResponder.resignFirstResponder),
to: nil,
from: nil,
for: nil)
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView(viewModel: .init())
}
}
| true
|
796d1786b002f4db3dc4059c5e4d125243a2206b
|
Swift
|
probe-pg/LeetCodeTest
|
/LeetCodeTest_iOS/LeetCodeTest_iOS/LinkedList/LinkedList_61.swift
|
UTF-8
| 1,728
| 3
| 3
|
[] |
no_license
|
//
// LinkedList_61.swift
// LeetCodeTest_iOS
//
// Created by sos1a2a3a on 2019/12/28.
// Copyright © 2019 lijiarui. All rights reserved.
//
import UIKit
/// https://leetcode-cn.com/problems/rotate-list/
public class LinkedList_61: NSObject {
public func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? {
//利用快慢指针实现
var temp = head
var len : Int = 0
while temp!.next != nil {
temp = temp?.next!
len += 1
}
var newk = k%len
if newk == 0 {
return head
}
var node = head
temp = head!
while newk>0 {
newk -= 1
temp = temp?.next!
}
while temp!.next != nil {
node = node?.next
temp = temp?.next!
}
print("temp:\(temp!.val) node:\(node!.val)")
let res = node!.next
node!.next = nil
temp!.next = head
return res
}
public func rotateRight2(_ head: ListNode?, _ k: Int) -> ListNode? {
// let newindex = len-k
//
// var lastNode = newNode
// var newHNode = newNode
// for _ in 0..<newindex {
//
// lastNode = lastNode.next!
// newHNode = lastNode.next!
// }
//
// let temp = newNode.next
//
// newNode.next = newHNode
//
// lastNode.next = nil
//
//
// newNode.next?.next?.next?.next = temp
return nil
}
}
| true
|
64659b8368a98c3bc24b31e03f7ef92b49e13656
|
Swift
|
arbyruns/Calendar_Help
|
/CalendarHelp/GetHansonData.swift
|
UTF-8
| 2,329
| 2.765625
| 3
|
[] |
no_license
|
//
// GetHansonData.swift
// runable
//
// Created by robevans on 8/6/21.
//
import Foundation
import SwiftUI
import Combine
// MARK: - TrainingData
struct TrainingDataModel: Codable, Identifiable {
let id, weeknumber: Int
let totalWeekMiles: Int
let day1, day2, day3, day4: Day
let day5, day6, day0: Day
let graphMiles: [Double]?
}
// MARK: - WeekExercise
struct Day: Codable {
let day: String
let dayMiles: Double
let exercise: String
}
typealias trainingData = [TrainingDataModel]
class DownloadHansonData: ObservableObject {
@Published var trainingdata: [TrainingDataModel] = []
var cancellabes = Set<AnyCancellable>()
init() {
print("loading init")
let defaults = UserDefaults.standard
guard let getRunUrl = defaults.string(forKey: "userDefault-planUrl") else { return }
print("getting ready to get data for \(getRunUrl)")
//We need make sure we have the current week of training on launch.
getPosts(runUrl: getRunUrl)
// weekNumber = getCurrentWeek(totalWeeks: defaults.integer(forKey: "totalWeeks"), raceDate: userRaceDate)
}
func getPosts(runUrl: String) {
guard let runUrl = URL(string: "https://api.npoint.io/60b107d904dbfb96cfe1") else { return }
print("getPost url \(runUrl)")
URLSession.shared.dataTaskPublisher(for: runUrl)
.subscribe(on: DispatchQueue.global(qos: .background))
.receive(on: DispatchQueue.main)
.tryMap { (data, response) -> Data in
print(response)
guard
let response = response as? HTTPURLResponse,
response.statusCode >= 200 && response.statusCode < 300 else {
throw URLError(.badServerResponse)
}
print(data)
return data
}
.decode(type: [TrainingDataModel].self, decoder: JSONDecoder())
.sink { (completion) in
} receiveValue: { [weak self] (returnedData) in
self?.trainingdata = returnedData
print(returnedData)
}
.store(in: &cancellabes)
}
}
/*
get current year week
get week of race
determine the week of training the user should be on
determine what
*/
| true
|
ef6f7a115f24606929fd21f0b68df5751470a23a
|
Swift
|
adityachavan198/iOS-projects
|
/swift-playground/Functions.playground/Contents.swift
|
UTF-8
| 654
| 3.46875
| 3
|
[] |
no_license
|
import UIKit
//func getMilk(){
// print("go to the shop")
// print("buy 2 cartons of milk")
// print("pay for the products")
//}
func getMilk(howManyMilkCartons : Int, howMuchMoneyRobotWasGiven: Int) -> Int {
print("go to the shop")
print("buy \(howManyMilkCartons) cartons of milk")
let priceToPay = howManyMilkCartons * 2
print("pay for \(priceToPay) for milk")
print("Come Home")
let change = howMuchMoneyRobotWasGiven - priceToPay
return change
}
var amountOfChange = getMilk(howManyMilkCartons: 1, howMuchMoneyRobotWasGiven: 10)
print("Hello Master, here's your $\(amountOfChange) change")
| true
|
3c852d93d54cc2699ad84d6f2f193e610c00bc65
|
Swift
|
pcugogo/ios17ss
|
/study/learning/PracticeProject/MoneyCalculation/MoneyCalculation/ViewController.swift
|
UTF-8
| 5,191
| 2.984375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// MoneyCalculation
//
// Created by 샤인 on 2017. 6. 15..
// Copyright © 2017년 IosCamp. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var names:[String] = [] //이름을 받는 배열
var randomNumberContainer:[Int] = [] //1~사람숫자만큼의 랜덤숫자를 받는 배열
@IBOutlet weak var countIndicatorLabel: UILabel! //사람 숫자 표시하는 라벨
@IBOutlet weak var listTableView: UITableView! //게임참여자 이름 목록
@IBOutlet weak var nameTextField: UITextField! //이름을 적는 텍스트
@IBOutlet weak var priceTextField: UITextField! //금액을 넣는 텍스트
override func viewDidLoad() {
super.viewDidLoad()
listTableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func calculate(price:Int) -> [Int] // 돈을 계산해주는 함수
{
var money = Int(priceTextField.text!)! //머니에 계산할 금액을 인트로 받는다
let numberOfPeople = names.count //참여자 수
var priceResult:[Int] = [] //계산후 각자 내야할 금액을 담는다
priceResult.append(0)
if numberOfPeople >= 3{ //사람수가 3명이상일때
for _ in 1...numberOfPeople-2 // 1명이 될때까지
{ // 돈금액을 2/1해주고 돌려서 priceResult에 담아준다
priceResult.append(money / 2)
money = money / 2
}
}else{
priceResult.append(money) //3명보다 적을경우 한명한테 몰아주려고 했는데 둘다 돈을 안내게 된다;
}
var thirdValue = 0
for i in 0..<priceResult.count
{
thirdValue = thirdValue + priceResult[i] //마지막 계산값 (2등 또는 3등 값을) 을 결과값 배열에 추가할것이다
}
thirdValue = price - thirdValue
priceResult.append(thirdValue)
priceResult.sort()
return priceResult
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if !(priceTextField.text?.isEmpty)! && !(names.isEmpty) && names.count > 1 { // 숫자만 들어올 수 있게하는것도 생각해보자
return true
}else{
let resultAlert:UIAlertController = UIAlertController(title: "오류", message: "추가 리스트와 금액을 입력해주세요", preferredStyle: .alert)
let resultBtnAlert:UIAlertAction = UIAlertAction(title: "예", style: .cancel, handler: nil)
resultAlert.addAction(resultBtnAlert)
self.present(resultAlert, animated: true, completion: nil)
return false
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let calculateViewController:CalculateViewController = segue.destination as! CalculateViewController
var randomNum = Int(arc4random_uniform((UInt32(names.count))))
randomNumberContainer.append(randomNum)
while randomNumberContainer.count < names.count
{
randomNum = Int(arc4random_uniform((UInt32(names.count))))
if !randomNumberContainer.contains(randomNum)
{
randomNumberContainer.append(randomNum)
}
}
calculateViewController.names = names //이름 배열,
calculateViewController.rankContainer = randomNumberContainer //순위
calculateViewController.priceResult = calculate(price: Int(priceTextField.text!) ?? 0) //순위 별 각각 낼 금액 낮은금액부터 높은금액으로 정렬된상태
}
@IBAction func addButtonTouched(_ sender: UIButton) {
let newName = nameTextField.text!
if !names.contains(newName) && newName != ""{
names.append(newName)
listTableView.reloadData()
countIndicatorLabel.text = String("\(names.count)명")
nameTextField.text?.removeAll()
}
}
@IBAction func removeBtn(_ sender: UIButton) { //리무브 버튼인데 이름을 잘못썻다
names.removeLast()
listTableView.reloadData()
countIndicatorLabel.text = String("\(names.count)명")
}
}
| true
|
c269b8a44e188a63144d04240a29a0d3c1a3d9f1
|
Swift
|
carabina/HYAlertView
|
/Example/HYAlertView/ViewController.swift
|
UTF-8
| 962
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// HYAlertView
//
// Created by CranberryYam on 07/24/2018.
// Copyright (c) 2018 CranberryYam. All rights reserved.
//
import UIKit
import HYAlertView
class ViewController: UIViewController, HYAlertController {
func alertViewDidClick(_ isOK: Bool) {
let result = isOK ? "pressed ok button" : "pressed cancel button"
print(result)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func clickAlertBtn(_ sender: Any) {
let title = "Caution!"
let content = "If you delete it, you can't restore it."
let alert = HYAlertView.init(title, content, nil, nil, nil)
alert.present(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
7a45789a3b9cc98007fbd9456f9a455b3da73812
|
Swift
|
extJo/Swift3_study
|
/Week2_T/Closure/Closure/main.swift
|
UTF-8
| 2,203
| 4.375
| 4
|
[] |
no_license
|
//
// main.swift
// Closure
//
// Created by 조성윤 on 2017. 1. 12..
// Copyright © 2017년 조성윤. All rights reserved.
//
import Foundation
// 파라미터와 리턴형이 없는 클로져
let simpleClosure = { print("Hello world!") }
simpleClosure()
// Hello world!
// 파라미터와 리턴형이 있는 클로져
let simClosure = { (str: String) -> String in
return "Hello, \(str)"
}
let result = simClosure("Swift Closure")
print(result)
// Hello, Swift Closure
// 클로져를 파라미터로 받는 함수
func performClosure(_ c: (String) -> (String)) {
let result = c("Swift closure")
print(result)
}
performClosure(simClosure)
// Hello, Swift closure
// 인라인 클로져. -> 함수선언을 통해서 파라미터의 자료형과 리턴형을 추론
performClosure({str in
return "Hello, \(str)!!"
})
// 인라인 클로져의 암시적 리턴
performClosure({str in
"inline closure, \(str)"
})
// 클로져 내부에서 사용할 수 있는 축약된 인자 이름을 제공
// 첫번째 인자의 이름은 $0, 두번째 인자의 이름은 $1
// 축약 인자 이름을 사용하면 파라미터 이름 선언과 in 키워드를 생략 할 수 있음
performClosure({ "Hello, \($0)" })
// 연산자 함수
let numbers = [10, 9, 44, 88, 40]
let orderedNumber = numbers.sorted(by: { (lhs: Int, rhs: Int) in
return lhs < rhs
})
print(orderedNumber)
let ordNumber = numbers.sorted(by: <)
print(ordNumber)
// trailing closure, closure의 내부 구현이 길어지는 경우
// 트레일링 클로져는 클로져가 함수의 마지막 파라미터로 전달되는 경우에만 사용 가능하다
performClosure() {"Trailing Closure, \($0)"}
// 함수에 클로져 파라미터 단 하나만 존재하는 경우 () 생략 가능
performClosure{"Hello Trailing Closure, \($0)"}
// 함수 선언이랑 헛갈릴수 있기때문에 주의하셔야 합니다.
// capture value
var num = 0
let closure = { print("inside of block: \(num)")}
num += 10
print("outside of block: \(num)")
closure()
func giveMe (_ c: (Int) -> (Int)){
let result = c(5)
print("call giveMe \(result)")
}
giveMe({
print("\($0)")
return $0
})
| true
|
0465fd79b93262db59790df777077d9620100ac0
|
Swift
|
LaurenWheeler/Scan-Sheet
|
/FoundationExtensions/ArrayExtension.swift
|
UTF-8
| 583
| 3.484375
| 3
|
[] |
no_license
|
extension Array {
func extractFrom(startIndex : Int, to endIndex : Int) -> [Element] {
let end = endIndex < self.count ? endIndex : (self.count > 0 ? self.count : 0)
let start = startIndex > -1 ? startIndex : 0
var newArray : [Element] = []
for i in start..<end {
newArray.append(self[i])
}
return newArray
}
}
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
| true
|
bb5a48b00c37d342929bcb362d1db4a13469dd4f
|
Swift
|
vebbyclrs/Maze-Ruiner
|
/Maze Ruiner/GameScene.swift
|
UTF-8
| 4,691
| 2.625
| 3
|
[] |
no_license
|
//
// GameScene.swift
// Maze Ruiner
//
// Created by Vebby Clarissa on 20/05/19.
// Copyright © 2019 Vebby Clarissa. All rights reserved.
//
import SpriteKit
import GameplayKit
import CoreMotion
struct PhysicsCategory {
static let none : UInt32 = 0
static let all : UInt32 = UInt32.max
static let ball : UInt32 = 0b01
static let endNode : UInt32 = 0b10
static let thorn : UInt32 = 0b11
static let wall : UInt32 = 0b100
}
class GameScene: SKScene, SKPhysicsContactDelegate {
let manager = CMMotionManager()
var player = SKSpriteNode()
var endNode = SKSpriteNode()
var col: Int = 1
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
print ("self:\(self)")
player = self.childNode(withName: "player") as! SKSpriteNode
player.texture = SKTexture(image: UIImage(named: "Ball")!)
endNode = self.childNode(withName: "endNode") as! SKSpriteNode
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = 0.1
manager.startAccelerometerUpdates(to: OperationQueue.main){
(Data, error) in
self.physicsWorld.gravity = CGVector(dx: CGFloat((Data?.acceleration.x)!) * 3, dy: CGFloat((Data?.acceleration.y)!) * 3)
}
}
func didBegin(_ contact: SKPhysicsContact) {
let bodyA : SKPhysicsBody
let bodyB : SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
bodyA = contact.bodyA
bodyB = contact.bodyB
}
else {
bodyA = contact.bodyB
bodyB = contact.bodyA
}
if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 {//ball and flag
ballTouchedFlag()
} else if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 3{ //ball and spikes
ballTouchedSpikes()
}
}
func ballTouchedSpikes () {
print ("you lose")
childNode(withName: "player")?.physicsBody?.affectedByGravity = false
childNode(withName: "player")?.physicsBody?.isDynamic = false
let popUpMessage = SKSpriteNode(color: UIColor.black, size: CGSize(width: 330, height: 200))
popUpMessage.name = "popUpMessage"
popUpMessage.alpha = 0.8
popUpMessage.drawBorder(color: UIColor.red, width: 3)
popUpMessage.position = CGPoint(x: self.size.width * 0.5, y: -(self.size.height * 0.5)) ;popUpMessage.zPosition = CGFloat(1)
addChild(popUpMessage)
let buttonTexture = SKTexture(imageNamed: "ButtonReplay")
let buttonPressedTexture = SKTexture(imageNamed: "ButtonReplay On Klick")
let replayButton = FTButtonNode(normalTexture: buttonTexture, selectedTexture: buttonPressedTexture, disabledTexture: buttonTexture)
replayButton.position = popUpMessage.position ; replayButton.zPosition = 2
replayButton.name = "replayButton"
addChild(replayButton)
replayButton.setButtonAction(target: self, triggerEvent: .TouchUpInside, action: #selector(replayTheGame))
}
@objc func replayTheGame() {
let newScene = SKScene(fileNamed: "GameScene")
let transition = SKTransition.fade(withDuration: 1.0)
self.childNode(withName: "popUpMessage")?.removeFromParent()
self.childNode(withName: "replayButton")?.removeFromParent()
self.view?.presentScene(newScene!, transition: transition)
}
func resetPLayer() {
player.position = CGPoint(x: 387, y: -864)
player.zPosition = 0
player.physicsBody?.isDynamic = true
player.physicsBody?.affectedByGravity = true
}
func ballTouchedFlag() {
print ("you won")
childNode(withName: "player")?.physicsBody?.affectedByGravity = false
childNode(withName: "player")?.physicsBody?.isDynamic = false
let popUpMessage = SKSpriteNode(color: UIColor.white, size: CGSize(width: 330, height: 200))
popUpMessage.name = "popUpMessage"
popUpMessage.alpha = 0.95
popUpMessage.drawBorder(color: UIColor.red, width: 3)
popUpMessage.position = CGPoint(x: self.size.width * 0.5, y: -(self.size.height * 0.5))
popUpMessage.zPosition = CGFloat(1)
addChild(popUpMessage)
let trophy = SKSpriteNode(imageNamed: "Trophy")
trophy.zPosition = 2
trophy.position = popUpMessage.position
addChild(trophy)
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
| true
|
d7bea706bc2bbeabb71fd253c3e3b379cadf11de
|
Swift
|
jjones-jr/AUHost
|
/Vendor/mc/mcFoundationExtensions/Sources/DateFormatter.swift
|
UTF-8
| 734
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
//
// DateFormatter.swift
// WaveLabs
//
// Created by Vlad Gorlov on 06.06.2020.
// Copyright © 2020 Vlad Gorlov. All rights reserved.
//
import Foundation
extension DateFormatter {
public static var iso8601: DateFormatter {
let formatter = DateFormatter()
// See: Working with Dates and Times Using the ISO 8601 Basic and Extended Notations
// http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}
public static func string(from date: Date, dateFormat: String) -> String {
let f = DateFormatter()
f.dateFormat = dateFormat
return f.string(from: date)
}
}
| true
|
d8c87374b67b024974b22d158f09a7e626d99651
|
Swift
|
proactive-solutions/SwiftUI-Combine
|
/VideoGalleryApp/Models/Video.swift
|
UTF-8
| 531
| 3.4375
| 3
|
[] |
no_license
|
import Foundation
struct Video: Codable, Hashable {
// MARK: - Properties
let id: Int
let name: String
let thumbnail: String
let videoDescription: String
let videoLink: String
// MARK: - Hashing Method
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
// MARK: - Coding Keys
enum CodingKeys: String, CodingKey {
case id
case name
case thumbnail
case videoDescription = "description"
case videoLink = "video_link"
}
}
| true
|
75395b557f0197b7ce7ecaf150a562b21982a9c8
|
Swift
|
PiggyPiggyRun/SwiftUICase
|
/SwiftUIBasicDemo/SwiftUIBasicDemo/HStackDemo.swift
|
UTF-8
| 408
| 2.671875
| 3
|
[] |
no_license
|
//
// HStackDemo.swift
// SwiftUIBasicDemo
//
// Created by RandyWei on 2021/3/30.
//
import SwiftUI
struct HStackDemo: View {
var body: some View {
HStack() {
ForEach(0..<4) {
Text("11111\($0)")
}
}
.font(.title)
}
}
struct HStackDemo_Previews: PreviewProvider {
static var previews: some View {
HStackDemo()
}
}
| true
|
959929ad348acb25ec7588f57bc4a2f2b7fe80c2
|
Swift
|
jfredric/StyleFitChallenge
|
/StyleFitChallenge/Alerts.swift
|
UTF-8
| 3,504
| 3
| 3
|
[] |
no_license
|
//
// Alerts.swift
// StyleFitChallenge
//
// Created by Joshua Fredrickson on 12/21/17.
// Copyright © 2017 Joshua Fredrickson. All rights reserved.
//
import Foundation
import UIKit
// allows you to get the topmost view at any current time
extension UIApplication {
static func topViewController(base: UIViewController? = UIApplication.shared.delegate?.window??.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
return topViewController(base: selected)
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
// reqeust a permission
func requestPermissionAlert(title: String, message: String?, from: UIViewController?, handler: @escaping (Bool)->Void) {
// Create the Alert Controller
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
// add the button actions - Left to right
// Cancel Button
alertController.addAction(UIAlertAction(title: "No Thanks", style: UIAlertActionStyle.default, handler: { (action) in
handler(false)
}))
// OK Button
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
handler(true)
}))
// Present the Alert
(from ?? UIApplication.topViewController()!).present(alertController, animated: true, completion: nil)
}
// send user a message
func messageAlert(title: String, message: String?, from: UIViewController?) {
// Create the Alert Controller
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
// add the button actions - Left to right
// OK Button
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// Present the Alert
(from ?? UIApplication.topViewController()!).present(alertController, animated: true, completion: nil)
}
// send user an error message
func errorAlert(message: String?, from: UIViewController?) {
// Create the Alert Controller
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
// add the button actions - Left to right
// OK Button
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// Present the Alert
(from ?? UIApplication.topViewController()!).present(alertController, animated: true, completion: nil)
}
// send user an error message
func fatalErrorAlert(message: String?, from: UIViewController?) {
// Create the Alert Controller
let alertController = UIAlertController(title: "Fatal Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
// add the button actions - Left to right
// OK Button
let crashAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (alertAction) in
fatalError(message!)
}
alertController.addAction(crashAction)
// Present the Alert
(from ?? UIApplication.topViewController()!).present(alertController, animated: true, completion: nil)
}
| true
|
895946ef6942a0f0be2e5d30f05643ec0cae75dd
|
Swift
|
stormwright/currencyConverterMVVM
|
/MoneyConverterEngine/MoneyConverterEngine/Rates Feed Cache/LocalRatesFeedLoader.swift
|
UTF-8
| 3,149
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// LocalRatesFeedLoader.swift
// MoneyConverterEngine
//
// Copyright © 2020 Stormwright. All rights reserved.
//
import Foundation
public class LocalRatesFeedLoader: RatesFeedLoader {
private let store: RatesFeedStore
private let currentDate: () -> Date
public typealias LoadResult = RatesFeedLoader.Result
public init(store: RatesFeedStore, currentDate: @escaping () -> Date) {
self.store = store
self.currentDate = currentDate
}
public func load(completion: @escaping (LoadResult) -> Void) {
store.retrieve { [weak self] (result) in
guard let self = self else { return }
switch result {
case let .failure(error):
completion(.failure(error))
case let .success(.some(cache)) where RatesFeedCachePolicy.validate(cache.timestamp, against: self.currentDate()):
completion(.success(cache.feed.toModels()))
case .success:
completion(.success([]))
}
}
}
}
extension LocalRatesFeedLoader: FeedCache {
public typealias SaveResult = FeedCache.Result
public func save(_ feed: [FeedRate], completion: @escaping (SaveResult) -> Void) {
store.deleteCachedFeed { [weak self] (deleteResult) in
guard let self = self else { return }
switch deleteResult {
case .success:
self.cache(feed, with: completion)
case let .failure(error):
completion(.failure(error))
}
}
}
private func cache(_ feed: [FeedRate], with completion: @escaping (SaveResult) -> Void) {
store.insert(feed.toLocal(), timestamp: currentDate()) { [weak self] insertionResult in
guard self != nil else { return }
completion(insertionResult)
}
}
}
extension LocalRatesFeedLoader {
public typealias ValidationResult = Result<Void, Error>
public func validateCache(completion: @escaping (ValidationResult) -> Void) {
store.retrieve { [weak self] result in
guard let self = self else { return }
switch result {
case .failure:
self.store.deleteCachedFeed(completion: completion)
case let .success(.some(cache)) where !RatesFeedCachePolicy.validate(cache.timestamp, against: self.currentDate()):
self.store.deleteCachedFeed(completion: completion)
case .success:
completion(.success(()))
}
}
}
}
private extension Array where Element == FeedRate {
func toLocal() -> [LocalFeedRate] {
return map { LocalFeedRate(code: $0.code, name: $0.name, rate: $0.rate, date: $0.date, inverseRate: $0.inverseRate) }
}
}
private extension Array where Element == LocalFeedRate {
func toModels() -> [FeedRate] {
return map { FeedRate(code: $0.code, name: $0.name, rate: $0.rate, date: $0.date, inverseRate: $0.inverseRate) }
}
}
| true
|
f217e521400265eebf7d6e4ec6bee301a0817075
|
Swift
|
opiotr/WeatherApp
|
/WeatherApp/Extensions/Double+Extension.swift
|
UTF-8
| 290
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Double+Extension.swift
// WeatherApp
//
// Created by Piotr Olech on 15/03/2019.
// Copyright © 2019 Piotr Olech. All rights reserved.
//
import Foundation
extension Double {
func roundToInt() -> Int {
var value = self
value.round()
return Int(value)
}
}
| true
|
ea19079f0406cdded0fd4898e367a9246ee2a79b
|
Swift
|
evrimfeyyaz/ah-guest-client-ios
|
/Guest Client/Models/TimeUTC.swift
|
UTF-8
| 1,964
| 3.53125
| 4
|
[] |
no_license
|
//
// Created by Evrim Persembe on 6/22/17.
// Copyright © 2017 Automated Hotel. All rights reserved.
//
import Foundation
struct TimeUTC: Comparable, CustomStringConvertible {
var hour: Int
var minute: Int
var totalMinutes: Int {
return minute + (hour * 60)
}
var totalSeconds: Int {
return totalMinutes * 60
}
var description: String {
return "\(hour):\(minute)"
}
init?(hourColonMinute: String) {
let parts = hourColonMinute.components(separatedBy: ":")
guard parts.count == 2, let hour = Int(parts[0]), let minute = Int(parts[1]) else { return nil }
self.hour = hour
self.minute = minute
}
init(date: Date) {
var calendar = Calendar(identifier: .iso8601)
calendar.timeZone = TimeZone(identifier: "UTC")!
self.hour = calendar.component(.hour, from: date)
self.minute = calendar.component(.minute, from: date)
}
func isBetween(startingTime: TimeUTC, endingTime: TimeUTC) -> Bool {
// Times involving the same day.
if startingTime <= endingTime {
return self >= startingTime && self <= endingTime
} else { // Ending time is in the next day.
return self >= startingTime || self <= endingTime
}
}
func description(inTimeZone timeZone: TimeZone) -> String {
let localTimeInTotalSeconds = totalSeconds + timeZone.secondsFromGMT()
let localTimeHour = (localTimeInTotalSeconds / (60*60)) % 24
let localTimeMinute = (localTimeInTotalSeconds % (60*60)) / 60
return String.init(format: "%02d:%02d", localTimeHour, localTimeMinute)
}
static func <(lhs: TimeUTC, rhs: TimeUTC) -> Bool {
return lhs.totalMinutes < rhs.totalMinutes
}
static func ==(lhs: TimeUTC, rhs: TimeUTC) -> Bool {
return lhs.totalMinutes == rhs.totalMinutes
}
}
| true
|
ec3baec12259bc2c1f53a1047dc5fb0d59405cbe
|
Swift
|
28th-BE-SOPT-iOS-Part/JangSeoHyun
|
/SOPT_28th_iOS_Assignment/SOPT_28th_iOS_Assignment/Sources/Cell/Friend/FriendProfileTVC.swift
|
UTF-8
| 873
| 2.578125
| 3
|
[] |
no_license
|
//
// FriendProfileTVC.swift
// SOPT_28th_iOS_Assignment
//
// Created by 장서현 on 2021/05/05.
//
import UIKit
class FriendProfileTVC: UITableViewCell {
@IBOutlet weak var friendProfileImg: UIImageView!
@IBOutlet weak var friendNameLabel: UILabel!
@IBOutlet weak var friendStateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setFriendProfileData(img : String, name : String, state : String) {
if let image = UIImage(named: img) {
friendProfileImg.image = image
}
friendNameLabel.text = name
friendStateLabel.text = state
}
}
| true
|
96e16a73c8b6c7cc5c8c611365a4eb9ec02c8f40
|
Swift
|
emilyw26/wax-and-wake
|
/waxNwake/WaxAndWake/GameViewController.swift
|
UTF-8
| 4,100
| 2.703125
| 3
|
[] |
no_license
|
//
// GameViewController.swift
// DiveIntoSpriteKit
//
// Created by Paul Hudson on 16/10/2017.
// Copyright © 2017 Paul Hudson. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
protocol GameDelegate {
func addAlarm()
func deleteAlarm()
}
class Alarm {
var time: String
var timeIndex: Int
var dayIndex: Int
var rowIndex: Int
init(time: String, timeIndex: Int, dayIndex: Int, rowIndex: Int) {
self.time = time
self.timeIndex = timeIndex
self.dayIndex = dayIndex
self.rowIndex = rowIndex
}
}
class GameViewController: UIViewController, CanReceive {
var timeNode: SKNode?
var alarmNodes: SKNode?
var gameDelegate: GameDelegate?
var alarms = [Alarm]()
var presetAlarmIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// set up delegate
gameDelegate = scene as? GameDelegate
scene.viewController = self
// Present the scene
view.presentScene(scene)
}
view.preferredFramesPerSecond = 120
timeNode = view.scene!.children[3]
}
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
@IBAction func addAlarm(_ sender: Any) {
presetAlarmIndex = nil
performSegue(withIdentifier: "goToAddAlarmVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToAddAlarmVC" {
let destinationVC = segue.destination as! AddAlarmViewController
if let timeLabelNode = timeNode as? SKLabelNode {
destinationVC.timeValuePassedOver = timeLabelNode.text!
if presetAlarmIndex != nil {
destinationVC.daySelection = alarms[presetAlarmIndex!].dayIndex
destinationVC.timeSelection = alarms[presetAlarmIndex!].timeIndex
destinationVC.rowSelection = alarms[presetAlarmIndex!].rowIndex
}
destinationVC.delegete = self
} else {
destinationVC.timeValuePassedOver = "Unsuccessful"
}
}
}
func addAlarm(timeStamp: String, timeOfDayIndex: Int, dayOfWeekIndex: Int, rowSelection: Int) {
alarms.append(Alarm(time: timeStamp, timeIndex: timeOfDayIndex, dayIndex: dayOfWeekIndex, rowIndex: rowSelection))
gameDelegate?.addAlarm()
}
func viewTouchedAlarm(alarmIndex: Int) {
presetAlarmIndex = alarmIndex
performSegue(withIdentifier: "goToAddAlarmVC", sender: self)
}
func receiveData(data: [String: Int]) {
if data["delete"]! == 1 {
gameDelegate?.deleteAlarm()
return
}
var time = "12:00"
var timeOfDay = 0
var dayOfWeek = 0
var row = 3
if let timeLabelNode = timeNode as? SKLabelNode {
time = timeLabelNode.text!
}
if let timeIndex = data["timOfDay"] {
timeOfDay = timeIndex
}
if let dayIndex = data["dayOfWeek"] {
dayOfWeek = dayIndex
}
if let rowIndex = data["row"] {
row = rowIndex
}
addAlarm(timeStamp: time, timeOfDayIndex: timeOfDay, dayOfWeekIndex: dayOfWeek, rowSelection: row)
}
}
| true
|
3ae4f281318a94a6811e46edf411517804898f48
|
Swift
|
wonhee009/Algorithm
|
/src/Programmers/PreTestSwift.swift
|
UTF-8
| 1,030
| 3.515625
| 4
|
[] |
no_license
|
import Foundation
func solution(_ answers:[Int]) -> [Int] {
var oneResult = 0
var twoResult = 0
var threeResult = 0
let oneAnswer = [1, 2, 3, 4, 5]
let twoAnswer = [2, 1, 2, 3, 2, 4, 2, 5]
let threeAnswer = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
for index in 0..<answers.count {
if(answers[index] == oneAnswer[index % oneAnswer.count]) {
oneResult += 1
}
if(answers[index] == twoAnswer[index % twoAnswer.count]) {
twoResult += 1
}
if(answers[index] == threeAnswer[index % threeAnswer.count]) {
threeResult += 1
}
}
var max = 0
max = (max < oneResult) ? oneResult : max
max = (max < twoResult) ? twoResult : max
max = (max < threeResult) ? threeResult : max
var answer: [Int] = []
if(max == oneResult) {
answer.append(1)
}
if(max == twoResult) {
answer.append(2)
}
if(max == threeResult) {
answer.append(3)
}
return answer
}
| true
|
befe775860029168f5cd59702bc3c9fcff82e137
|
Swift
|
Clumsyndicate/AI-Trainer
|
/AI Trainer/FeedbackViewController.swift
|
UTF-8
| 1,589
| 2.640625
| 3
|
[] |
no_license
|
//
// FeedbackViewController.swift
// AI Trainer
//
// Created by Zhu Scott on 2019/7/30.
// Copyright © 2019 Zhu Scott. All rights reserved.
//
import UIKit
import AVKit
import SocketIO
class FeedbackViewController: UIViewController {
var networking: Networking!
var socket: SocketIOClient!
override func viewDidLoad() {
super.viewDidLoad()
let networking = Networking(address: "http://10.20.69.32:5000")
networking.addHandlers()
networking.connect()
networking.socket.on(clientEvent: .connect) { (data, ack) in
print("Connected to Socket~!")
networking.selectVid(videoName: "name")
}
let socket = networking.socket
socket!.on("feedback") { (data, Ack) in
self.playMusic(data: data[0] as! Data)
}
}
@IBAction func startTraining(_ sender: UIButton) {
socket.emit("practise")
}
var audio: AVAudioPlayer!
func playMusic(data: Data) {
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("voice.mp3")
do {
try data.write(to: fileURL, options: .atomic)
} catch {
print("Error")
print(error)
}
do{
audio = try AVAudioPlayer(contentsOf: fileURL)
audio.prepareToPlay()
audio.play()
}
catch {
print("Error")
}
}
}
| true
|
19733ee509e277cb24d8affe4da130ae9ee8e841
|
Swift
|
pkasila/FileTree
|
/FileTree/FileTree.swift
|
UTF-8
| 12,585
| 2.796875
| 3
|
[] |
no_license
|
//
// FileTree.swift
// FileTree
//
// Created by Devin Abbott on 8/17/18.
// Copyright © 2018 Devin Abbott. All rights reserved.
//
import AppKit
import Foundation
import Witness
private extension NSTableColumn {
convenience init(title: String, resizingMask: ResizingOptions = .autoresizingMask) {
self.init(identifier: NSUserInterfaceItemIdentifier(rawValue: title))
self.title = title
self.resizingMask = resizingMask
}
}
private extension NSOutlineView {
enum Style {
case standard
case singleColumn
}
convenience init(style: Style) {
self.init()
switch style {
case .standard:
return
case .singleColumn:
let column = NSTableColumn(title: "OutlineColumn")
column.minWidth = 100
addTableColumn(column)
outlineTableColumn = column
columnAutoresizingStyle = .uniformColumnAutoresizingStyle
backgroundColor = .clear
autoresizesOutlineColumn = true
focusRingType = .none
rowSizeStyle = .custom
headerView = nil
}
}
}
public class FileTree: NSBox {
public typealias Path = String
public typealias Name = String
// MARK: Lifecycle
public init(rootPath: Path? = nil) {
super.init(frame: .zero)
if let rootPath = rootPath {
self.rootPath = rootPath
}
sharedInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
private func sharedInit() {
setUpViews()
setUpConstraints()
update()
setUpWitness()
initialized = true
}
// MARK: Public
public var onAction: ((Path) -> Void)?
public var onSelect: ((Path) -> Void)?
public var onCreateFile: ((Path) -> Void)?
public var onDeleteFile: ((Path) -> Void)?
public var defaultRowHeight: CGFloat = 28.0 { didSet { update() } }
public var defaultThumbnailSize = NSSize(width: 24, height: 24) { didSet { update() } }
public var defaultThumbnailMargin: CGFloat = 4.0 { didSet { update() } }
public var defaultFont: NSFont = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: .regular))
/** Determine the name to display based on the file's full path. */
public var displayNameForFile: ((Path) -> Name)? { didSet { update() } }
/** Sets the height of the row. If not provided, height is set to `defaultRowHeight`. */
public var rowHeightForFile: ((Path) -> CGFloat)? { didSet { update() } }
public var rowViewForFile: ((Path) -> NSView)? { didSet { update() } }
public var imageForFile: ((Path, NSSize) -> NSImage)? { didSet { update() } }
public var sortFiles: ((Name, Name) -> Bool)? { didSet { update() } }
public var filterFiles: ((Name) -> Bool)? { didSet { update() } }
public var showHiddenFiles = false { didSet { update() } }
public var rootPath = "/" {
didSet {
if !initialized { return }
outlineView.autosaveName = autosaveName
setUpWitness()
update()
}
}
public func reloadData() {
update()
}
// MARK: Private
private var witness: Witness?
private var initialized = false
private var outlineView = NSOutlineView(style: .singleColumn)
private var scrollView = NSScrollView(frame: .zero)
private var autosaveName: NSTableView.AutosaveName {
return NSTableView.AutosaveName(rootPath)
}
private func contentsOfDirectory(atPath path: String) -> [String] {
var children = (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? []
if let filterFiles = filterFiles {
children = children.filter(filterFiles)
} else if !showHiddenFiles {
children = children.filter { name in
return !name.starts(with: ".")
}
}
if let sortComparator = sortFiles {
children = children.sorted(by: sortComparator)
} else {
children = children.sorted()
}
return children
}
@objc func handleAction(_ sender: AnyObject?) {
let row = outlineView.selectedRow
guard let path = outlineView.item(atRow: row) as? Path else { return }
onAction?(path)
}
public func outlineViewSelectionDidChange(_ notification: Notification) {
let row = outlineView.selectedRow
guard let path = outlineView.item(atRow: row) as? Path else { return }
onSelect?(path)
}
func setUpViews() {
boxType = .custom
borderType = .lineBorder
contentViewMargins = .zero
borderWidth = 0
outlineView.autosaveExpandedItems = true
outlineView.dataSource = self
outlineView.delegate = self
outlineView.autosaveName = autosaveName
outlineView.target = self
outlineView.action = #selector(handleAction(_:))
outlineView.reloadData()
scrollView.hasVerticalScroller = true
scrollView.drawsBackground = false
scrollView.addSubview(outlineView)
scrollView.documentView = outlineView
outlineView.sizeToFit()
addSubview(scrollView)
}
func setUpConstraints() {
translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
}
func update() {
outlineView.reloadData()
}
}
extension FileTree {
private func setUpWitness() {
// Swift.print("Watching events at", rootPath)
self.witness = Witness(paths: [rootPath], flags: .FileEvents, latency: 0) { events in
// print("file system events received: \(events)")
DispatchQueue.main.async {
events.forEach { event in
if event.flags.contains(.ItemCreated) {
// Swift.print("Create event", event)
self.createFile(atPath: event.path)
} else if event.flags.contains(.ItemRemoved) {
// Swift.print("Delete event", event)
self.deleteFile(atPath: event.path)
}
}
}
}
}
private func deleteFile(atPath path: Path) {
onDeleteFile?(path)
// let url = URL(fileURLWithPath: path)
// Swift.print("Delete file", url.lastPathComponent)
guard let parent = outlineView.parent(forItem: path) else { return }
outlineView.reloadItem(parent, reloadChildren: true)
outlineView.sizeToFit()
}
private func createFile(atPath path: Path) {
onCreateFile?(path)
let url = URL(fileURLWithPath: path)
// Swift.print("Create file", url.lastPathComponent)
let parentUrl = url.deletingLastPathComponent()
let parentPath = parentUrl.path
// Swift.print("Try to find \(parentPath)")
guard let parent = first(where: { ($0 as? String) == parentPath }) else { return }
outlineView.reloadItem(parent, reloadChildren: true)
outlineView.sizeToFit()
}
private func first(where: (Any) -> Bool) -> Any? {
func firstChild(_ item: Any, where: (Any) -> Bool) -> Any? {
if `where`(item) { return item }
let childCount = outlineView.numberOfChildren(ofItem: item)
for i in 0..<childCount {
if
let child = outlineView.child(i, ofItem: item),
let found = firstChild(child, where: `where`) {
return found
}
}
return nil
}
guard let root = outlineView.child(0, ofItem: nil) else { return nil }
return firstChild(root, where: `where`)
}
}
extension FileTree: NSOutlineViewDataSource {
public func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil { return 1 }
guard let path = item as? String else { return 0 }
return contentsOfDirectory(atPath: path).count
}
public func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item == nil { return rootPath }
let path = item as! String
return path + "/" + contentsOfDirectory(atPath: path)[index]
}
public func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
guard let path = item as? String else { return false }
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
return isDir.boolValue
} else {
return false
}
}
public func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? {
return item as? String
}
public func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? {
return object as? String
}
public func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
return item
}
}
private class FileTreeCellView: NSTableCellView {
public var onChangeBackgroundStyle: ((NSView.BackgroundStyle) -> Void)?
override var backgroundStyle: NSView.BackgroundStyle {
didSet { onChangeBackgroundStyle?(backgroundStyle) }
}
}
extension FileTree: NSOutlineViewDelegate {
private func rowHeightForFile(atPath path: String) -> CGFloat {
return rowHeightForFile?(path) ?? defaultRowHeight
}
private func imageForFile(atPath path: String, size: NSSize) -> NSImage {
return NSWorkspace.shared.icon(forFile: path)
}
private func rowViewForFile(atPath path: String) -> NSView {
let thumbnailSize = defaultThumbnailSize
let thumbnailMargin = defaultThumbnailMargin
let name = displayNameForFile?(path) ?? URL(fileURLWithPath: path).lastPathComponent
let view = FileTreeCellView()
let textView = NSTextField(labelWithString: name)
let imageView = NSImageView(image: imageForFile?(path, thumbnailSize) ?? imageForFile(atPath: path, size: thumbnailSize))
imageView.imageScaling = .scaleProportionallyUpOrDown
view.addSubview(textView)
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: thumbnailMargin).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: thumbnailSize.width).isActive = true
imageView.heightAnchor.constraint(equalToConstant: thumbnailSize.height).isActive = true
textView.translatesAutoresizingMaskIntoConstraints = false
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: thumbnailMargin * 2 + thumbnailSize.width).isActive = true
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
textView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
textView.font = defaultFont
textView.maximumNumberOfLines = 1
textView.lineBreakMode = .byTruncatingMiddle
view.onChangeBackgroundStyle = { style in
switch style {
case .light:
textView.textColor = .black
case .dark:
textView.textColor = .white
default:
break
}
}
return view
}
public func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let path = item as? String else { return NSView() }
return rowViewForFile?(path) ?? rowViewForFile(atPath: path)
}
public func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
guard let path = item as? String else { return defaultRowHeight }
return rowHeightForFile(atPath: path)
}
}
| true
|
af72311b0998038b65717335eec95b6f226ddee5
|
Swift
|
ravitripathi/GitBrowser
|
/Shared/NetworkStore.swift
|
UTF-8
| 1,501
| 2.8125
| 3
|
[] |
no_license
|
//
// NetworkStore.swift
// GitBrowser
//
// Created by Ravi Tripathi on 19/07/20.
//
import SwiftUI
import Combine
class NetworkStore: ObservableObject {
@Published private(set) var repos: [Repo] = []
@Published private(set) var isLoadingRepos: Bool = false
@Published private(set) var following: [FollowingUser] = []
@Published private(set) var isLoadingFollowList: Bool = false
func fetch() {
self.isLoadingRepos = true
NetworkManager.shared.getRepoList { (repos) -> (Void) in
if let repos = repos {
DispatchQueue.main.async {
self.repos = repos
self.isLoadingRepos = false
}
}
}
}
func fetchFollowing() {
self.isLoadingFollowList = true
NetworkManager.shared.getFollowingList { (followingUser) -> (Void) in
if let fU = followingUser {
DispatchQueue.main.async {
self.following = fU
self.isLoadingFollowList = false
}
}
}
}
func fetchRepo(forUsername username: String) {
self.isLoadingRepos = true
NetworkManager.shared.getRepoList(forUsername: username) { (repoList) -> (Void) in
DispatchQueue.main.async {
if let rL = repoList {
self.repos = rL
self.isLoadingRepos = false
}
}
}
}
}
| true
|
065fd0599f36a1c8800db51f2aff37024d1367e9
|
Swift
|
sayyidmaulana/introtoprogrammatically
|
/ProgrammaticPageControl/BerandaBar/FirstCell.swift
|
UTF-8
| 1,321
| 2.59375
| 3
|
[] |
no_license
|
//
// FirstCell.swift
// ProgrammaticPageControl
//
// Created by sayyid maulana khakul yakin on 26/12/19.
// Copyright © 2019 sayyid maulana khakul yakin. All rights reserved.
//
import UIKit
class FirstCell: UICollectionViewCell {
fileprivate var bgView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.layer.cornerRadius = 10
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 0.3
view.layer.shadowOffset = CGSize.zero
view.layer.shadowRadius = 5
view.isUserInteractionEnabled = true
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
addSubview(bgView)
// bgView.setAnchor(top: topAnchor, left: leadingAnchor, bottom: nil, right: trailingAnchor, paddingTop: 10, paddingLeft: 10, paddingBottom: 0, paddingRight: 10, width: frame.width - 20, height: frame.height - 20)
// addSubview(lblTitleTP)
// lblTitleTP.setAnchor(top: imgView.bottomAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0)
}
}
| true
|
afbeeb9707e270ddd01716b82c6ecde571f78f9d
|
Swift
|
LamKanSing/Collection-View-Flickr-and-web-page-
|
/CollectionView/Animal.swift
|
UTF-8
| 457
| 2.859375
| 3
|
[] |
no_license
|
//
// Animal.swift
// CollectionView
//
// Created by kan sing lam
// Copyright © 2018年 kan sing lam All rights reserved.
//
struct Animal {
var name : String
var wikiLinkWord : String
var photoKeyword : String
init(_ name : String, _ wikiLinkWord : String, _ photoKeyword : String) {
self.name = name
self.wikiLinkWord = "https://en.wikipedia.org/wiki/" + wikiLinkWord
self.photoKeyword = photoKeyword
}
}
| true
|
de52cb40b12a7dd8e45db11249f554a36dbba97d
|
Swift
|
awelch6/BoseAR
|
/BoseWearable-iOS-bin-4.0.8/Examples/Common/Extensions/UIViewController+Alert.swift
|
UTF-8
| 1,613
| 3.125
| 3
|
[] |
no_license
|
//
// UIViewController+Alert.swift
// Common
//
// Created by Paul Calnan on 9/19/18.
// Copyright © 2018 Bose Corporation. All rights reserved.
//
import UIKit
/// Alert dialog utilities
extension UIViewController {
/**
Show an alert for the specified error. If the error is non-nil, its localized description will be shown as the message. Otherwise, a generic error message is shown.
- parameter error: The error to be displayed.
- parameter dismissHandler: The callback to be invoked when the alert's action is performed.
*/
public func show(_ error: Error?, dismissHandler: (() -> Void)? = nil) {
let message: String?
if let localized = error as? LocalizedError? {
message = localized?.errorDescription
}
else {
message = error?.localizedDescription
}
showAlert(title: "Error", message: message ?? "An unknown error occurred", dismissHandler: dismissHandler)
}
/**
Show an alert with the specified title and message.
- parameter title: The title of the alert.
- parameter message: The alert message.
- parameter dismissHandler: The callback to be invoked when the alert's action is performed.
*/
public func showAlert(title: String, message: String? = nil, dismissHandler: (() -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
dismissHandler?()
}))
present(alert, animated: true)
}
}
| true
|
62eef88f8469a3d5edfde7aca3035b3a1108f9d6
|
Swift
|
seubseub/Moneybook
|
/Moneybook/AppDelegate.swift
|
UTF-8
| 9,427
| 2.515625
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// Moneybook
//
// Created by Macbook Pro retina on 2016. 11. 9..
// Copyright © 2016년 com. All rights reserved.
//
import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
/*
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Register for remote notifications
if #available(iOS 8.0, *) {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// Fallback
let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
application.registerForRemoteNotificationTypes(types)
}
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
return true
}
// [START receive_message]
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%@", userInfo)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotificaiton(notification: NSNotification) {
let refreshedToken = FIRInstanceID.instanceID().token()!
print("InstanceID token: \(refreshedToken)")
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
}
// [START disconnect_from_fcm]
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
*/
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//create the notificationCenter
let center = UNUserNotificationCenter.current()
center.delegate = self
// set the type as sound or badge
center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in
// Enable or disable features based on authorization
}
FIRMessaging.messaging().remoteMessageDelegate = self
FIRApp.configure()
/*
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
*/
application.registerForRemoteNotifications()
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 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 applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.unknown)
//let refreshedToken = FIRInstanceID.instanceID().token()!
//print("refreshed token : \(refreshedToken)")
print( "노티피케이션 등록을 성공함, 디바이스 토큰 : \(deviceTokenString)" )
}
*/
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print( "노티피케이션 APNS 등록 중 에러 발생 : \(error.localizedDescription)" )
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
//FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.prod)
//let refreshedToken = FIRInstanceID.instanceID().token()!
//print("refreshed token : \(refreshedToken)")
print( "노티피케이션 등록을 성공함, 디바이스 토큰 : \(deviceTokenString)" )
}
/*
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])
{
print("Message ID: \(userInfo["gcm.message_id"]!)")
print("노티피케이션을 받았습니다. :\(userInfo)")
}
*/
func tokenRefreshNotificaiton(notification: NSNotification) {
//let refreshedToken = FIRInstanceID.instanceID().token()!
//print("인스턴스 아이디토큰 : \(refreshedToken)")
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFCM()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
// custom code to handle push while app is in the foreground
print("\(notification.request.content.userInfo)")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Handle push from background or closed")
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("\(response.notification.request.content.userInfo)")
}
func connectToFCM() {
FIRMessaging.messaging().connect { (error) in
if(error != nil) {
print("Cannot connected FCM")
print(error.debugDescription)
print(error!)
} else {
print("connected to FCM")
}
}
}
/*
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFCM()
// 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 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.
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
*/
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%@", remoteMessage.appData)
}
}
| true
|
02cb8e4fb664395194c744f15a4feddde887eb4c
|
Swift
|
ajchrumka/SelfieVideo
|
/SelfieCamera/SelfieCamera/src/view/ui/topbar/button/ExitButton.swift
|
UTF-8
| 729
| 2.609375
| 3
|
[] |
no_license
|
import UIKit
//make exitBtn
//right
//green / red with text
class ExitButton:ClickButton{
override init(frame: CGRect) {
let rect = ExitButton.rect
super.init(frame: rect)
backgroundColor = .clear
self.setImage(#imageLiteral(resourceName: "cancel"), for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static var rect:CGRect {
let btnWidth:CGFloat = 30
let topLeft:CGPoint = {
let margin:CGFloat = 40
return CGPoint.init(x: margin, y: margin)
}()
let rect = CGRect(x:topLeft.x, y:topLeft.y, width:btnWidth, height:btnWidth)
return rect
}
}
| true
|
8a6a3639b67364d0765e6b7a819aada226a3af39
|
Swift
|
ekeitho/CrossPaths
|
/CrossPaths/TabController.swift
|
UTF-8
| 3,417
| 2.765625
| 3
|
[] |
no_license
|
//
// TabController.swift
// CrossPaths
//
// Created by Keith Abdulla on 1/31/15.
// Copyright (c) 2015 Keith Abdulla. All rights reserved.
//
import UIKit
// REFERENCE - https://github.com/yeahdongcn/UIColor-Hex-Swift/blob/master/UIColorExtension.swift
// UIColorExtension.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = advance(rgba.startIndex, 1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (countElements(hex)) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
println("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
class TabController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.selectedIndex = 2;
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
var nav = self.navigationController?.navigationBar
nav!.barStyle = UIBarStyle.BlackTranslucent
nav!.barTintColor = UIColor(rgba: "#8DE6BB")
nav!.tintColor = UIColor.redColor()
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "logo.png")
imageView.image = image
navigationItem.titleView = imageView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
cb632334758ddedc228d5a84c884b11780f197e2
|
Swift
|
LDlalala/LDZBLiving
|
/LDZBLiving/LDZBLiving/Classes/Main/LDPageView/LDPageView.swift
|
UTF-8
| 1,800
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// LDPageView.swift
// LDPageView
//
// Created by 李丹 on 17/8/2.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
class LDPageView: UIView {
private var titles : [String]
private var childVcs : [UIViewController]
private var parent : UIViewController
private var style : LDPageStyle
init(frame : CGRect ,titles : [String] ,style : LDPageStyle , childVcs : [UIViewController], parent : UIViewController) {
// 在super前初始化变量
assert(titles.count == childVcs.count,"标题&控制器个数不相同,请检测")
self.titles = titles
self.childVcs = childVcs;
self.parent = parent
self.style = style
self.parent.automaticallyAdjustsScrollViewInsets = false
super.init(frame: frame)
setupUI()
}
private func setupUI() {
// 添加标题视图
let titleFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: style.titleHeight)
let titleView = LDTitleView(titles: titles, frame: titleFrame, style: style)
titleView.backgroundColor = UIColor.black
addSubview(titleView)
// 添加内容视图
let contentFrame = CGRect(x: 0, y: style.titleHeight, width: self.bounds.width, height: self.bounds.height - style.titleHeight)
let contentView = LDContentView(frame: contentFrame, childVcs: childVcs, parent: parent)
contentView.backgroundColor = UIColor.randomColor()
addSubview(contentView)
// 设置contentView&titleView关系
titleView.delegate = contentView
contentView.delegate = titleView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
ff678279cb9375b6316a288f0aeda659960aa3a3
|
Swift
|
lfap/ColorInterpolation
|
/ColorInterpolation/ViewController.swift
|
UTF-8
| 2,167
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// ColorInterpolation
//
// Created by Luiz Felipe Albernaz Pio on 13/09/18.
// Copyright © 2018 Luiz Felipe Albernaz Pio. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var valueLabel: UILabel!
@IBOutlet weak var containerView: UIView!
var progressiveChart: ProgressiveChart!
let titles: [String] = ["-18.5", "18.6 - 24.9", "25 - 29.9", "30 - 35+"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// containerView.backgroundColor = UIColor.clear
let chartFrame = CGRect(origin: CGPoint.zero, size: containerView.frame.size)
progressiveChart = ProgressiveChart(frame: chartFrame)
progressiveChart.progressiveHeight = true
progressiveChart.set(dataSource: self, andDelegate: self)
containerView.addSubview(progressiveChart)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTouchGeneratePercentage(_ button: UIButton) {
let value = Double.random(in: 0.0...1.0)
valueLabel.text = String(format: "%.2f", value)
progressiveChart.setTotalProgressAt(value)
}
}
extension ViewController: ProgressiveChartDataSource {
func progressiveChartNumberOfSections(forChart chart: ProgressiveChart) -> Int {
return titles.count
}
func progressiveChartNumberOfBars(forChart chart: ProgressiveChart, atSection section: Int) -> Int {
if section < 2 {
return 4
} else {
return 6
}
}
func progressiveChartTitleForSection(section: Int) -> String {
return titles[section]
}
}
extension ViewController: ProgressiveChartDelegate {
func progressiveChartSpaceBetweenBars(forChart chart: ProgressiveChart) -> CGFloat {
return 10
}
func progressiveChartAlphaForUnusedSections(chat: ProgressiveChart) -> CGFloat {
return 0.0
}
}
| true
|
52b3e99a9d69bb4488e9f90994febfb17d543c79
|
Swift
|
apple/swift-nio-extras
|
/Sources/NIOSOCKS/Messages/AuthenticationMethod.swift
|
UTF-8
| 1,255
| 2.703125
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// The SOCKS authentication method to use, defined in RFC 1928.
public struct AuthenticationMethod: Hashable, Sendable {
/// No authentication required
public static let noneRequired = AuthenticationMethod(value: 0x00)
/// Use GSSAPI
public static let gssapi = AuthenticationMethod(value: 0x01)
/// Username / password authentication
public static let usernamePassword = AuthenticationMethod(value: 0x02)
/// No acceptable authentication methods
public static let noneAcceptable = AuthenticationMethod(value: 0xFF)
/// The method identifier, valid values are in the range 0:255.
public var value: UInt8
public init(value: UInt8) {
self.value = value
}
}
| true
|
da3505805ecaa487b652d9469b122d2d68527761
|
Swift
|
gilglick/Bthere
|
/Birthdays/AddContactViewController.swift
|
UTF-8
| 4,648
| 2.703125
| 3
|
[] |
no_license
|
import UIKit
import Contacts
import ContactsUI
import FirebaseAuth
protocol AddContactViewControllerDelegate {
func didFetchContacts(_ contacts: [CNContact])
}
class AddContactViewController: UIViewController, UserCallBack {
func onFinish(user: User) {
// self.firebaseService.addContacts(user: user, contactId: )
}
@IBOutlet weak var txtLastName: UITextField!
var delegate: AddContactViewControllerDelegate!
var user : User!
var firebaseService : FirebaseService!
override func viewDidLoad() {
super.viewDidLoad()
firebaseService = FirebaseService(callback: self)
txtLastName.delegate = self
generateDoneButton()
}
func generateDoneButton(){
let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(AddContactViewController.performDoneItemTap))
navigationItem.rightBarButtonItem = doneBarButtonItem
}
}
extension AddContactViewController: CNContactPickerDelegate {
@IBAction func showContacts(_ sender: AnyObject) {
let contactPickerViewController = CNContactPickerViewController()
contactPickerViewController.predicateForEnablingContact = NSPredicate(format: "birthday != nil")
contactPickerViewController.delegate = self
contactPickerViewController.displayedPropertyKeys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactBirthdayKey, CNContactImageDataKey]
present(contactPickerViewController, animated: true, completion: nil)
}
func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {
delegate.didFetchContacts([contact])
navigationController?.popViewController(animated: true)
}
}
// MARK: - UITextFieldDelegate functions
extension AddContactViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
AppDelegate.appDelegate.requestForAccess { (accessGranted) -> Void in
if accessGranted {
let predicate = CNContact.predicateForContacts(matchingName: self.txtLastName.text!)
let keys = [CNContactFormatter.descriptorForRequiredKeys(for: CNContactFormatterStyle.fullName), CNContactEmailAddressesKey, CNContactBirthdayKey] as [Any]
var contacts = [CNContact]()
var warningMessage: String!
let contactsStore = AppDelegate.appDelegate.contactStore
do {
contacts = try contactsStore.unifiedContacts(matching: predicate, keysToFetch: keys as! [CNKeyDescriptor])
if contacts.count == 0 {
warningMessage = "No contacts were found matching the given name."
}
} catch {
warningMessage = "Unable to fetch contacts."
}
if let warningMessage = warningMessage {
DispatchQueue.main.async {
Helper.show(message: warningMessage)
}
} else {
DispatchQueue.main.async {
self.delegate.didFetchContacts(contacts)
self.navigationController?.popViewController(animated: true)
}
}
}
}
return true
}
// MARK: - On click done button
@objc func performDoneItemTap() {
AppDelegate.appDelegate.requestForAccess { (accessGranted) -> Void in
if accessGranted {
let predicate = CNContact.predicateForContacts(matchingName: self.txtLastName.text!)
let keys = [CNContactFormatter.descriptorForRequiredKeys(for: CNContactFormatterStyle.fullName), CNContactEmailAddressesKey, CNContactBirthdayKey] as [Any]
var contacts = [CNContact]()
var warningMessage: String!
let contactsStore = AppDelegate.appDelegate.contactStore
do {
contacts = try contactsStore.unifiedContacts(matching: predicate, keysToFetch: keys as! [CNKeyDescriptor])
if contacts.count == 0 {
warningMessage = "No contacts were found matching the given name."
}
} catch {
warningMessage = "Unable to fetch contacts."
}
if let warningMessage = warningMessage {
DispatchQueue.main.async {
Helper.show(message: warningMessage)
}
} else {
DispatchQueue.main.async {
self.firebaseService.addContacts(user: self.user, contactId: contacts.first!.identifier)
self.delegate.didFetchContacts(contacts)
self.navigationController?.popViewController(animated: true)
}
}
}
}
}
}
| true
|
b3bc541214459f5b5c38eb4373b666d730872234
|
Swift
|
vouliont/MoUP
|
/MoU/Model/ViewModel/LoadingCellProtocol.swift
|
UTF-8
| 152
| 2.765625
| 3
|
[] |
no_license
|
import Foundation
protocol LoadingCellProtocol {
associatedtype Item
var item: Item? { get set }
var cellType: CellType { get set }
}
| true
|
15d2f42968709f543e11c3040db9463f9de49d41
|
Swift
|
ruuvi/com.ruuvi.station.ios
|
/station/Extensions/Int+Extension.swift
|
UTF-8
| 301
| 2.953125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
import Foundation
extension Int {
var stringValue: String {
return "\(self)"
}
}
extension Optional where Wrapped == Int {
var stringValue: String {
if let self = self {
return "\(self)"
} else {
return "N/A".localized()
}
}
}
| true
|
b4123c5072c179ff0a598e03df315e80001811aa
|
Swift
|
teute/Remind-Me
|
/Remind Me/Reminders.swift
|
UTF-8
| 3,539
| 3.234375
| 3
|
[] |
no_license
|
//
// Reminders.swift
// Remind Me
//
// Created by Salieu Kamara on 13/12/2016.
// Copyright © 2016 Coventry University. All rights reserved.
//
//http://stackoverflow.com/questions/29986957/save-custom-objects-into-nsuserdefaults
import Foundation
public class Reminder: NSObject, NSCoding {
var title: String
var module: String
var category: Int
var deadline: Date
var dueIn: TimeInterval
public init(title: String, module: String, category: Int, deadline: Date) {
self.title = title
self.module = module
self.category = category
self.deadline = deadline
self.dueIn = deadline.timeIntervalSince(Date())
}
required convenience public init(coder aDecoder: NSCoder) {
let title = aDecoder.decodeObject(forKey: "title") as! String
let module = aDecoder.decodeObject(forKey: "module") as! String
let category = aDecoder.decodeInteger(forKey: "category")
let deadline = aDecoder.decodeObject(forKey: "deadline") as! Date
self.init(title: title, module: module, category: category, deadline: deadline)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: "title")
aCoder.encode(module, forKey: "module")
aCoder.encode(category, forKey: "category")
aCoder.encode(deadline, forKey: "deadline")
}
}
enum ReminderError: Error {
case emptyString
case outOfRande(index: Int)
}
public class Reminders {
var reminders:[Reminder]
let userDefaults = UserDefaults.standard
public static let sharedInstance = Reminders()
private init() {
self.reminders = []
}
public var count: Int {
get {
return self.reminders.count
}
}
public func add(reminder: Reminder) throws {
if (reminder.title.isEmpty || reminder.module.isEmpty || reminder.category < 0) {
throw ReminderError.emptyString
}
self.reminders.append(reminder)
}
public func getReminder(at index: Int) throws -> Reminder {
if (index < 0) || (index > (self.reminders.count - 1)) {
throw ReminderError.outOfRande(index: index)
}
return self.reminders[index]
}
public func clearList() {
self.reminders.removeAll()
}
public func insert(reminder: Reminder, at index: Int) throws {
if (index < 0) || (index > self.reminders.count) {
throw ReminderError.outOfRande(index: index)
}
self.reminders.insert(reminder, at: index)
}
public func update(reminder: Reminder, at index: Int) throws {
if (index < 0) || (index > (self.reminders.count - 1)) {
throw ReminderError.outOfRande(index: index)
}
self.reminders[index] = reminder
}
public func remove(at index: Int) throws {
if (index < 0) || (index > (self.reminders.count - 1)) {
throw ReminderError.outOfRande(index: index)
}
self.reminders.remove(at: index)
}
public func save() {
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: reminders)
userDefaults.set(encodedData, forKey: "reminders")
userDefaults.synchronize()
}
public func load() {
if let decoded = userDefaults.object(forKey: "reminders") as? Data {
self.reminders = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Reminder]
}
}
}
| true
|
45b4fe111d627844fc074746042129d3d5ed3b79
|
Swift
|
shahrukhalam/AppUsingSimplestNetworking
|
/AppUsingSimplestNetworking/Simplest Networking/URLComponents + Init.swift
|
UTF-8
| 517
| 2.703125
| 3
|
[] |
no_license
|
//
// URLComponents + Init.swift
// URLComponents + Init
//
// Created by Shahrukh Alam on 24/09/21.
//
import Foundation
extension URLComponents {
init(scheme: String = "https",
host: String = "api.myapp.com",
path: String,
queryItems: [URLQueryItem]? = nil) {
var components = URLComponents()
components.scheme = scheme
components.host = host
components.path = path
components.queryItems = queryItems
self = components
}
}
| true
|
e3fd37532863dd5bbf6f3623e96ac61465549f80
|
Swift
|
ashley-jelks-truss/Cat-Age-Converter-Calculator
|
/Cat Age Calculator/ViewController.swift
|
UTF-8
| 1,217
| 3.296875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Cat Age Calculator
//
// Created by Ashley Jelks on 11/25/15.
// Copyright © 2015 Ashley Jelks. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var catAgeTextField: UITextField!
@IBOutlet var resultLabel: UILabel!
@IBAction func findAge(sender: AnyObject) {
var catAge = Int(catAgeTextField.text!)!
//the first "!" tells Swift that there is a value in the text box to be unwrapped
//the second "!" tells Swift that it is going to be a valid value that can be converted from a String into an Integer
catAge = catAge * 7
resultLabel.text = "Your cat is \(catAge) cat years old."
}
//simple conversions and calculations work, but should write some logic that will not allow user to submit unless they have included valid 0-9 integers.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
d62b1c4f38a7e22aff4dcfbb23ff6e42fc56c063
|
Swift
|
buscarini/pairofwings
|
/pairofwings/pairofwings/Observable.swift
|
UTF-8
| 844
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
//
// Observable.swift
// pairofwings
//
// Created by Jose Manuel Sánchez Peñarroja on 23/10/14.
// Copyright (c) 2014 José Manuel Sánchez. All rights reserved.
//
import Foundation
public enum ObservationType {
case WillSet
case DidSet
}
public protocol ObservableProtocol {
typealias T
func addObserver(closure : (T?,T?) -> ())
func addObserver(type: ObservationType,closure : (T?,T?) -> ())
}
public class Observable<T> : ObservableProtocol {
var observers = [ ObservationType : Array<(T?, T?) -> ()>]()
public func addObserver(closure : (T?,T?) -> ()) {
self.addObserver(.DidSet, closure)
}
public func addObserver(type: ObservationType,closure : (T?,T?) -> ()) {
if observers[type]==nil {
observers[type] = Array<(T?, T?) -> ()>()
}
var expandedArray = observers[type]!
expandedArray.append(closure)
observers[type] = expandedArray
}
}
| true
|
2ee6bd51421487868b40a151d67735065c7227ff
|
Swift
|
beom-mingyu/iglistkitHelpMe
|
/iglistkityogi/demo/Post.swift
|
UTF-8
| 2,269
| 2.8125
| 3
|
[] |
no_license
|
//
// Post.swift
// iglistkityogi
//
// Created by mingyu beom on 2020/11/30.
//
import Foundation
import ObjectMapper
import IGListDiffKit
import SwiftDate
class Post: Mappable, ListDiffable, CustomDebugStringConvertible {
//object >. CustomDebugStringConvertible issue
var id: Int!
var selectedDate: Date!
var photos: [String] = [] //Not image: count == 1 && photos[0] = ""
var memo: String? = nil
var tags: [String]
//Array[String] to Strings
var oneHashTags: String {
get {
return tags.map{ "#"+$0 }.joined(separator: " ")
}
}
func getHashTags() -> [String]{
return tags.map{"#"+$0}
}
var debugDescription: String {
return "empty"
}
init(id: Int, selectedDate: Date, photos:[String],memo: String, tags: [String]) {
self.id = id
self.selectedDate = selectedDate
self.memo = memo
self.tags = tags
self.photos = photos
}
required convenience init?(map: Map) {
self.init(map: map)
}
func mapping(map: Map) {
id <- map["id"]
selectedDate <- (map["selectedDate"], ISODateTransform())
photos <- map["photos"]
memo <- map["memo"]
tags <- map["tags"]
}
//ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return id as NSNumber
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
guard let object = object as? Post else { return false }
return self.id == object.id && self.memo == object.memo && self.tags == object.tags && self.selectedDate == object.selectedDate && self.photos == object.photos
}
//ListDiffable end
}
open class ISODateTransform: TransformType {
public typealias Object = Date
public typealias JSON = String
public init() {
}
public func transformFromJSON(_ value: Any?) -> Date? {
guard let datestring = value as? String else { return nil }
return datestring.toDate(region: Region.current)?.date
}
public func transformToJSON(_ value: Date?) -> String? {
let isoFormatter = ISO8601DateFormatter()
let string = isoFormatter.string(from: value!)
return string
}
}
| true
|
bf1491bbbeb6755ffe86493bc3490dada605b184
|
Swift
|
kokimiya/WeddinggGogoApp
|
/WeddinggGogoApp/PhotoViewController.swift
|
UTF-8
| 1,895
| 3
| 3
|
[] |
no_license
|
//
// PhotoViewController.swift
// WeddinggGogoApp
//
// Created by Koki Miyazawa on 2019/09/16.
// Copyright © 2019 Koki_Miyazawa. All rights reserved.
//
import UIKit
class PhotoViewController: UIViewController {
@IBOutlet weak var weddingImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
//0-9の写真をランダムで表示
let RAMDOM = String(arc4random_uniform(9))
let IMAGE = UIImage(named: "WEDDINGPHOTO\(RAMDOM)")
weddingImage.image = IMAGE
//UIImageViewにタップイベントを追加
weddingImage.isUserInteractionEnabled = true
weddingImage.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.saveImage(_:))))
}
//画像の保存処理
@objc func saveImage(_ sender: UITapGestureRecognizer) {
let targetImageView = sender.view! as! UIImageView
let targetImage = targetImageView.image!
UIImageWriteToSavedPhotosAlbum(targetImage, self, #selector(self.showResultOfSaveImage(_:didFinishSavingWithError:contextInfo:)), nil)
}
//保存を試みた結果をダイヤログに表示
@objc func showResultOfSaveImage(_ image: UIImage, didFinishSavingWithError error: NSError!, contextInfo: UnsafeMutableRawPointer) {
var title = "♡保存完了だっちゃ♡"
var message = "ちなみに確率は1/69でした"
if error != nil {
title = "エラーだよ!みやざわーるどに連絡だ!!"
message = "保存に失敗しました"
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "末永くお幸せに:)byみやざわーるど", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| true
|
ce22bd633a05315bfdc40202f695b3b227b0349b
|
Swift
|
JacksonPk/ProblemSolving
|
/BaekJoon/BJ2798.swift
|
UTF-8
| 755
| 3.65625
| 4
|
[] |
no_license
|
//https://www.acmicpc.net/problem/2798
import Foundation
func combination(_ maxNum : Int, _ intArr : [Int]) -> Int{
//while , for 문 말고 다른게 있나?
var nearestVal = 0
for i in 0 ..< intArr.count - 2 {
for j in i+1 ..< intArr.count - 1 {
for k in j+1 ..< intArr.count {
let value = intArr[i] + intArr[j] + intArr[k]
if value > nearestVal , value <= maxNum {
nearestVal = value
}
}
}
}
return nearestVal
}
//main
let firstInput = readLine()!.split(separator: " ").compactMap(){Int($0)}
let secondInput = readLine()!.split(separator: " ").compactMap(){Int($0)}
print(combination(firstInput[1], secondInput))
| true
|
1680d3077b19f7400a50febdc0989921761c7402
|
Swift
|
chrismlee26/makeschool
|
/labs/Make-ChatRooms/Make-ChatRooms/Cells/MessageTableViewCell.swift
|
UTF-8
| 2,515
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// MessageTableViewCell.swift
// Make-ChatRooms
//
// Created by Matthew Harrilal on 2/3/19.
// Copyright © 2019 Matthew Harrilal. All rights reserved.
//
import Foundation
import UIKit
// To represent state of the sender of the message
//enum MessageSender {
// case ourself
// case someoneElse
//}
class MessageTableViewCell: UITableViewCell {
// var messageSender: MessageSender = .ourself
let messageContentLabel = UILabel()
let nameLabel = UILabel()
var message: Message?
func apply(message: Message) { // When applying a message to the cell update below information
self.message = message
nameLabel.text = message.senderUsername
messageContentLabel.text = message.messageContent
setNeedsLayout()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
messageContentLabel.clipsToBounds = true
messageContentLabel.textColor = .white
messageContentLabel.numberOfLines = 0
nameLabel.textColor = .lightGray
nameLabel.font = UIFont(name: "Helvetica", size: 10)
clipsToBounds = true
addSubview(messageContentLabel)
addSubview(nameLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Measurements and layout for messages
private class func height(forText text: String, fontSize: CGFloat, maxSize: CGSize) -> CGFloat {
let font = UIFont(name: "Helvetica", size: fontSize)!
let attrString = NSAttributedString(string: text, attributes:[NSAttributedStringKey.font: font,
NSAttributedStringKey.foregroundColor: UIColor.white])
let textHeight = attrString.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil).size.height
return textHeight
}
class func height(for message: Message) -> CGFloat {
let maxSize = CGSize(width: 2*(UIScreen.main.bounds.size.width/3), height: CGFloat.greatestFiniteMagnitude)
let nameHeight = height(forText: message.senderUsername, fontSize: 10, maxSize:maxSize)
let messageHeight = height(forText: message.messageContent, fontSize: 17, maxSize: maxSize)
return nameHeight + messageHeight + 32 + 16
}
}
| true
|
cfc622a1c5948311e7255472dba661ea5d0f6a88
|
Swift
|
weijun8687/SwiftDemo
|
/WJWeibo/WJWeibo/Class/Tools(工具)/NetWork/WJNetworkManager.swift
|
UTF-8
| 1,673
| 2.9375
| 3
|
[] |
no_license
|
//
// WJNetworkManager.swift
// WJWeibo
//
// Created by WJ on 17/2/8.
// Copyright © 2017年 WJ. All rights reserved.
//
import UIKit
// 导入的是第三方框架的文件及名字
import AFNetworking
let appkey = "1743792288"
let appSecret = "565be51eadbbcbc93e614af8c0c78b25"
let access_token = "2.00GQdKRExisNREccd171a345gX39KC"
enum WJHTTPMethod {
case GET
case POST
}
class WJNetworkManager: AFHTTPSessionManager {
// 单例
static let shareManager: WJNetworkManager = {
// 实例化对象
let instance = WJNetworkManager()
// 设置响应反序列化支持的类型
instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
return instance
}()
/// 封装 AFN 的 GET/ POST 请求方法
///
/// - Parameters:
/// - method: GET / POST
/// - URLString: URLString
/// - parameters: 参数字典
/// - completion: 完成回调 (json(字典/数组), 是否成功)
func request(method: WJHTTPMethod = .GET, URLString: String, parameters: [String: Any], completion:@escaping (_ json: Any? , _ isSuccess: Bool)->()) {
let success = {(task: URLSessionDataTask, json:Any?)->() in
completion(json, true)
}
let failure = {(task: URLSessionDataTask?, error: Error)->() in
completion(nil, false)
}
if method == .GET {
get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
}else{
post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
}
}
}
| true
|
cd4770a84ead915ec81e1c100194569cdb345ace
|
Swift
|
furqanmk/tmdb
|
/The Movie Database/History.swift
|
UTF-8
| 699
| 2.9375
| 3
|
[] |
no_license
|
//
// History.swift
// The Movie Database
//
// Created by Furqan on 17/05/2017.
// Copyright © 2017 Careem. All rights reserved.
//
import Foundation
class History {
static var items: [String] {
guard let history = UserDefaults.standard.array(forKey: "history") as? [String] else {
return []
}
return history
}
static func addItem(string query: String) {
var history = items
if history.contains(query) {
return
}
if history.count == 10 {
history.remove(at: 9)
}
history.insert(query, at: 0)
UserDefaults.standard.setValue(history, forKey: "history")
}
}
| true
|
dc4f33c530764f07653efa917afee8c1baa0157f
|
Swift
|
iwheelbuy/Projects
|
/Sources/Textus/Core/Textus+Representable.swift
|
UTF-8
| 3,630
| 2.78125
| 3
|
[] |
no_license
|
import UIKit
public protocol TextusRepresentable {
//
var alignment: Textus.Alignment { get }
///
var parts: [Textus.Part] { get }
///
var lineHeight: CGFloat { get }
///
var truncating: Textus.Truncating { get }
///
var wrapping: Textus.Wrapping { get }
}
extension TextusRepresentable {
public var attributedString: NSAttributedString {
let lineHeight = self.lineHeight
let paragraphStyle: NSParagraphStyle = {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = self.alignment
paragraphStyle.lineBreakMode = self.wrapping.lineBreakMode
paragraphStyle.lineSpacing = 0
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.minimumLineHeight = lineHeight
return paragraphStyle
}()
return parts
.reduce(into: NSMutableAttributedString(), { (full, part) in
let part = part.attributedString(
lineHeight: lineHeight,
paragraphStyle: paragraphStyle
)
full.append(part)
})
}
public var attributedText: NSAttributedString {
return self.attributedString
}
@available(*, deprecated, message: "Надо заменить вытаскивание параметров из NSAttributedString на вытаскивание параметров напрямую из Textus")
public var attributes: [NSAttributedString.Key: Any] {
let attirbutedString = self.attributedString
let length = attirbutedString.length
let range = NSRange(location: 0, length: length)
var dictionary = [NSAttributedString.Key: Any]()
attirbutedString.enumerateAttributes(in: range, options: []) { [length] (attributes, range, _) in
if range.location == 0, range.length == length {
for (key, value) in attributes {
dictionary[key] = value
}
}
}
return dictionary
}
public var string: String {
return parts.map({ $0.string }).joined()
}
public var urls: [URL] {
return parts.compactMap({ $0.load?.url })
}
public func appending<T>(_ string: T) -> Textus where T: TextusRepresentable {
return self.with(
lineHeight: max(self.lineHeight, string.lineHeight),
parts: self.parts + string.parts
)
}
public func prefix(_ maxLength: Int) -> Textus {
var index: Int = 0
var parts = [Textus.Part]()
parts.reserveCapacity(self.parts.count)
for part in self.parts where index < maxLength {
let count = maxLength - index
if part.string.count <= count {
parts.append(part)
index += part.string.count
} else {
let string = String(part.string.prefix(count))
parts.append(part.with(string: string))
index += string.count
}
}
return self.with(parts: parts)
}
public func with(alignment: Textus.Alignment? = nil, lineHeight: CGFloat? = nil, parts: [Textus.Part]? = nil, truncating: Textus.Truncating? = nil, wrapping: Textus.Wrapping? = nil) -> Textus {
return Textus(
alignment: alignment ?? self.alignment,
lineHeight: lineHeight ?? self.lineHeight,
parts: parts ?? self.parts,
truncating: truncating ?? self.truncating,
wrapping: wrapping ?? self.wrapping
)
}
}
| true
|
49d7e294e036e2c87271f46ad0ddedf84ed6f3f9
|
Swift
|
BrunoCerberus/TestsWorkshop
|
/TestsWorkshop/TestsWorkshop/Model.swift
|
UTF-8
| 150
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
struct Restaurant: Codable {
let id: String
let name: String
var visited: Bool
}
typealias Restaurants = [Restaurant]
| true
|
c77b8584a99c274bb14fef20eab12369462eb93a
|
Swift
|
StebinAlex/TicTacToe-SwiftUI
|
/TicTacToe/TicTacToe/Views/StartView.swift
|
UTF-8
| 1,704
| 3.125
| 3
|
[] |
no_license
|
//
// StartView.swift
// TicTacToe
//
// Created by LTS on 06/06/21.
//
import SwiftUI
struct StartView: View {
@State private var isShowingGameView = false
@State private var animate: Bool = false
var body: some View {
NavigationView {
GeometryReader { proxy in
VStack {
NavigationLink(
destination: GameView(),
isActive: $isShowingGameView,
label: { })
SView(proxy: proxy)
Spacer()
Button("START") {
startPressed()
}
.foregroundColor(.white)
.font(.title)
.frame(width: 200, height: 50)
.background(Color.red)
.opacity( animate ? 0 : 1 )
.clipShape(Capsule())
.animation(.easeInOut(duration: 1.0))
Spacer()
}
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .center)
}
}
}
fileprivate func startPressed() {
self.animate = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.isShowingGameView = true
}
}
}
struct StartView_Previews: PreviewProvider {
static var previews: some View {
StartView()
}
}
struct SView: View {
var proxy: GeometryProxy
var body: some View {
Text("Tic Tac Toe")
.foregroundColor(.red)
.font(.largeTitle.bold())
}
}
| true
|
9cc0bf9757d7c76d180da894d77cca1f0009875b
|
Swift
|
ngocphu2810/Buckets-Swift
|
/Source/BloomFilterTypeExtensions.swift
|
UTF-8
| 1,750
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// BloomFilterTypeExtensions.swift
// Buckets
//
// Created by Mauricio Santos on 2016-02-03.
// Copyright © 2016 Mauricio Santos. All rights reserved.
//
import Foundation
extension Bool: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension Double: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension Float: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension Int: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension Int8: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension Int16: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension Int32: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension Int64: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension UInt: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension UInt8: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension UInt16: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension UInt32: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension UInt64: BloomFilterType {
public var bytes: [UInt8] {return bytesFromStruct(self)}
}
extension String: BloomFilterType {
public var bytes: [UInt8] {return [UInt8](self.utf8)}
}
private func bytesFromStruct<T>(value: T) -> [UInt8] {
var theValue = value
return withUnsafePointer(&theValue) {
Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>($0), count: sizeof(T)))
}
}
| true
|
70c1364bb4f60f169ad69e1a948267f3404a9e0f
|
Swift
|
caioalcn/FindHub
|
/FindHub/Extensions/UITableView+Extension.swift
|
UTF-8
| 1,001
| 2.78125
| 3
|
[] |
no_license
|
//
// UITableView+Extension.swift
// FindHub
//
// Created by Caio Alcântara on 04/04/21.
//
import UIKit
extension UITableView {
func setEmptyMessage(_ message: String, isLoading: Bool) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
messageLabel.text = message
messageLabel.textColor = UIColor(named: AssetsColors.label.rawValue)
messageLabel.numberOfLines = 2;
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "Futura", size: 18)
messageLabel.sizeToFit()
let spinner = UIActivityIndicatorView(style: .large)
spinner.color = UIColor(named: AssetsColors.label.rawValue)
spinner.startAnimating()
if isLoading {
self.backgroundView = spinner
} else {
self.backgroundView = messageLabel
}
}
func restore() {
self.backgroundView = nil
}
}
| true
|
8a6a2bc03192a288665efe459554c6fd61560169
|
Swift
|
awong05/BigNerdRanch
|
/WorldTrotter/WorldTrotter/MapViewController.swift
|
UTF-8
| 6,484
| 2.765625
| 3
|
[] |
no_license
|
//
// MapViewController.swift
// WorldTrotter
//
// Created by Andy Wong on 10/23/16.
// Copyright © 2016 Big Nerd Ranch. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController {
private let kDistanceMeters: CLLocationDistance = 500
private let annotationCoordinates = { () -> [CLLocationCoordinate2D] in
let coordinates = [(42.3601, -71.0589), (40.7128, -74.0059), (37.7749, -122.4194)]
let coordinateDegrees = coordinates.map { (CLLocationDegrees($0.0), CLLocationDegrees($0.1)) }
return coordinateDegrees.map { CLLocationCoordinate2D(latitude: $0.0, longitude: $0.1) }
}()
private var currentAnnotationIndex = 0
var mapView: MKMapView!
var locationManager = CLLocationManager()
// MARK: - View Life Cycle
override func loadView() {
mapView = MKMapView()
view = mapView
// Adding segmented control subview.
let standardString = NSLocalizedString("Standard", comment: "Standard map view")
let satelliteString = NSLocalizedString("Satellite", comment: "Satellite map view")
let hybridString = NSLocalizedString("Hybrid", comment: "Hybrid map view")
let segmentedControl = UISegmentedControl(items: [standardString, satelliteString, hybridString])
segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(mapTypeChanged(_:)), for: .valueChanged)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedControl)
let margins = view.layoutMarginsGuide
segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8).isActive = true
segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
// Adding user location zoom button.
let userZoomButton = UIButton()
userZoomButton.backgroundColor = .white
userZoomButton.setTitle("🏠", for: .normal)
userZoomButton.addTarget(self, action: #selector(zoomOnUserLocation(_:)), for: .touchUpInside)
userZoomButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(userZoomButton)
userZoomButton.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor, constant: -8).isActive = true
userZoomButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
// Adding pin cycling button.
let pinCyclingButton = UIButton()
pinCyclingButton.backgroundColor = .white
pinCyclingButton.setTitle("📍", for: .normal)
pinCyclingButton.addTarget(self, action: #selector(cycleThroughPinViews(_:)), for: .touchUpInside)
pinCyclingButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pinCyclingButton)
pinCyclingButton.bottomAnchor.constraint(equalTo: userZoomButton.topAnchor, constant: -8).isActive = true
pinCyclingButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager.delegate = self
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
} else if CLLocationManager.authorizationStatus() != .denied {
mapView.showsUserLocation = true
}
for coordinate in annotationCoordinates {
let annotation = PinAnnotation(coordinate: coordinate)
mapView.addAnnotation(annotation)
}
}
// MARK: - Event Handlers
func mapTypeChanged(_ segControl: UISegmentedControl) {
switch segControl.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
default:
break
}
}
func zoomOnUserLocation(_ button: UIButton) {
let userAnnotationView = mapView.view(for: mapView.userLocation)
userAnnotationView?.isHidden = false
let center = mapView.userLocation.coordinate
let zoomRegion = MKCoordinateRegionMakeWithDistance(center, kDistanceMeters, kDistanceMeters)
mapView.setRegion(zoomRegion, animated: true)
}
func cycleThroughPinViews(_ button: UIButton) {
let annotationList = mapView.annotations.filter { $0 is PinAnnotation }
for annotation in annotationList {
let annotationView = mapView.view(for: annotation)
annotationView?.isHidden = true
}
let currentAnnotation = annotationList[currentAnnotationIndex]
let annotationView = mapView.view(for: currentAnnotation)
annotationView?.isHidden = false
currentAnnotationIndex += 1
if currentAnnotationIndex == annotationList.count {
currentAnnotationIndex = 0
}
}
}
// MARK: - MKMapView Delegate
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "Landmark"
if annotation is PinAnnotation {
if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) {
return annotationView
} else {
let annotationView = MKPinAnnotationView(annotation: annotation as! PinAnnotation, reuseIdentifier: identifier)
annotationView.isHidden = true
return annotationView
}
}
return nil
}
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for view in views {
if view.annotation is MKUserLocation {
view.isHidden = true
}
}
}
}
// MARK: - CLLocationManager Delegate
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
status != .notDetermined ? mapView.showsUserLocation = true : print("Authorization for location services denied.")
}
}
| true
|
e41818656d3d55164822838256266b2bbaa08b96
|
Swift
|
keke728/ATLS5519_MobileAppDevelopment
|
/Spring18/Lab1/CheeseBread/FirstViewController.swift
|
UTF-8
| 2,700
| 2.75
| 3
|
[] |
no_license
|
//
// FirstViewController.swift
// CheeseBread
//
// Created by Keke Wu on 1/29/18.
// Copyright © 2018 Keke Wu. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let breadComponent = 0
let cheeseComponent = 1
var cheeseBread = [String:[String]]()
var bread = [String]()
var cheese = [String]()
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
@IBOutlet weak var breadPicker: UIPickerView!
@IBOutlet weak var breadLabel: UILabel!
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == breadComponent {
return bread.count
}else{
return cheese.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == breadComponent {
return bread[row]
}
else{
return cheese[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == breadComponent {
let selectedBread = bread[row]
cheese = cheeseBread[selectedBread]!
breadPicker.reloadComponent(cheeseComponent)
breadPicker.selectRow(0, inComponent:cheeseComponent, animated:true)
}
let breadrow = pickerView.selectedRow(inComponent: breadComponent)
let cheeserow = pickerView.selectedRow(inComponent: cheeseComponent)
breadLabel.text = "You bread is \(bread[breadrow]) with \(cheese[cheeserow])"
breadLabel.numberOfLines = 0
breadLabel.lineBreakMode = .byWordWrapping
breadLabel.textAlignment = NSTextAlignment.center
breadLabel.sizeToFit()
}
override func viewDidLoad() {
super.viewDidLoad()
if let pathURL = Bundle.main.url(forResource:"Bread", withExtension:"plist"){
let plistdecoder = PropertyListDecoder()
do {
let data = try Data(contentsOf: pathURL)
cheeseBread = try plistdecoder.decode([String:[String]].self, from: data)
bread = Array(cheeseBread.keys)
cheese = cheeseBread[bread[0]]! as [String]
}catch{
print(error)
}
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
1e6efaba96e0e2a7787ba33ceeb5c355c04d6884
|
Swift
|
IanMadlenya/Portfolio-2
|
/PortfolioTests/NetworkManagerTests.swift
|
UTF-8
| 3,949
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// NetworkManagerTests.swift
// Portfolio
//
// Created by John Woolsey on 3/30/16.
// Copyright © 2016 ExtremeBytes Software. All rights reserved.
//
import XCTest
@testable import Portfolio
class NetworkManagerTests: XCTestCase {
// MARK: - Properties
// MARK: - Test Configuration
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// MARK: - Network Manager Class Unit Tests
/**
Network Manager fetchPosition(for,completion) function unit tests.
*/
func testFetchPositionForCompletion() {
// Fetch empty data
var positionEmpty: Position?
var errorEmpty: Error?
let expectationEmpty = expectation(description: "Wait for empty data to load.")
NetworkManager.shared.fetchPosition(for: "") { (position, error) in
positionEmpty = position
errorEmpty = error
expectationEmpty.fulfill()
}
// Fetch invalid symbol data
var positionInvalidSymbol: Position?
var errorInvalidSymbol: Error?
let expectationInvalidSymbol = expectation(description: "Wait for invalid symbol data to load.")
NetworkManager.shared.fetchPosition(for: "INVALID") { (position, error) in
positionInvalidSymbol = position
errorInvalidSymbol = error
expectationInvalidSymbol.fulfill()
}
// Fetch AAPL data
var positionAAPL: Position?
var errorAAPL: Error?
let expectationAAPL = expectation(description: "Wait for AAPL data to load.")
NetworkManager.shared.fetchPosition(for: "AAPL") { (position, error) in
positionAAPL = position
errorAAPL = error
expectationAAPL.fulfill()
}
// Fetch BND data
var positionBND: Position?
var errorBND: Error?
let expectationBND = expectation(description: "Wait for BND data to load.")
NetworkManager.shared.fetchPosition(for: "BND") { (position, error) in
positionBND = position
errorBND = error
expectationBND.fulfill()
}
// Fetches completed
waitForExpectations(timeout: 5, handler: nil)
// Empty data
XCTAssertNil(positionEmpty, "Empty position is not nil.")
XCTAssertNotNil(errorEmpty, "Empty error is nil.")
if let errorEmpty = errorEmpty as? NetworkError {
XCTAssertEqual(errorEmpty, NetworkError.invalidRequest, "Empty error is not an invalid request.")
}
// Invalid symbol data
XCTAssertNil(positionInvalidSymbol, "Invalid symbol position is not nil.")
XCTAssertNil(errorInvalidSymbol, "Invalid symbol error is not nil.")
// AAPL data
XCTAssertNotNil(positionAAPL, "AAPL position is nil.")
XCTAssertNil(errorAAPL, "AAPL error is not nil.")
positionAAPL?.memberType = .watchList
if let positionAAPL = positionAAPL {
XCTAssertFalse(positionAAPL.isEmpty, "AAPL position is empty.")
XCTAssertTrue(positionAAPL.isComplete, "AAPL position is not complete.")
XCTAssertEqual(positionAAPL.statusForDisplay, positionAAPL.timeStampForDisplay, "AAPL position status is incorrect.")
}
// BND data
XCTAssertNotNil(positionBND, "BND position is nil.")
XCTAssertNil(errorBND, "BND error is not nil.")
positionAAPL?.memberType = .watchList
if let positionBND = positionBND {
XCTAssertFalse(positionBND.isEmpty, "BND position is empty.")
XCTAssertFalse(positionBND.isComplete, "BND position is complete.")
XCTAssertEqual(positionBND.statusForDisplay, "Incomplete Data", "BND position status is incorrect.")
}
}
}
| true
|
f2e52ae0756a56ac2a35060c64b9ecdc064791a5
|
Swift
|
andreyleganov/weather.test.ios
|
/SochiWeather/Library/Model/HourlyWeather.swift
|
UTF-8
| 419
| 2.53125
| 3
|
[] |
no_license
|
//
// HourlyWeather.swift
// SochiWeather
//
// Created by Andrey Leganov on 2/20/21.
//
import Foundation
struct HourlyWeather: Codable {
var dt: Int
var temp: Double
var feelsLike: Double
var pressure: Int
var humidity: Int
var uvi: Double
var clouds: Int
var windSpeed: Double
var windDeg: Int
var weather: [Weather]
var pop: Double
var snow: Snow?
var rain: Rain?
}
| true
|
0d2abdbe2e93471a2726b678ea3d9c6d2fb21f30
|
Swift
|
railwaymen/timetable-ios
|
/TimeTableTests/Tests/Models/BussinessModels/Vacation/VacationParametersTests.swift
|
UTF-8
| 730
| 2.609375
| 3
|
[] |
no_license
|
//
// VacationParametersTests.swift
// TimeTableTests
//
// Created by Piotr Pawluś on 23/04/2020.
// Copyright © 2020 Railwaymen. All rights reserved.
//
import XCTest
import Restler
@testable import TimeTable
class VacationParametersTests: XCTestCase {
private var queryEncoder: Restler.QueryEncoder {
Restler.QueryEncoder(jsonEncoder: self.encoder)
}
}
extension VacationParametersTests {
func testEncoding() throws {
//Arrange
let sut = VacationParameters(year: 2020)
//Act
let queryItems = try self.queryEncoder.encode(sut)
//Assert
XCTAssertEqual(queryItems.count, 1)
XCTAssert(queryItems.contains(.init(name: "year", value: "\(2020)")))
}
}
| true
|
afa13dd4abbd72023af637a85328372a4e6586cd
|
Swift
|
bertiGrazi/DrugData-
|
/DrugData/DrugData/Scenes/ResultadoPesquisa/View/ResultadoPesquisaViewController.swift
|
UTF-8
| 2,760
| 2.640625
| 3
|
[] |
no_license
|
//
// ResultadoPesquisaViewController.swift
// DrugData
//
// Created by Grazi Berti on 16/11/20.
//
import UIKit
class ResultadoPesquisaViewController: UIViewController {
// MARK: IBOutlet
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var labelLocation: UILabel!
@IBOutlet weak var imageViewAvatar: UIImageView!
@IBOutlet weak var tableViewResult: UITableView!
// MARK: Atributos
var searchTerm: String = ""
var array = [Cabecalho] ()
//var arrayMedice = [Remedios] ()
var resultadoPesquisaViewModel: ResultadoPesquisaViewModel?
override func viewDidLoad() {
super.viewDidLoad()
resultadoPesquisaViewModel = ResultadoPesquisaViewModel()
tableViewResult.delegate = self
tableViewResult.dataSource = self
setup(dados: (Cabecalho(name: "Maria", location: "São Paulo", profileImage: "1.png")) )
loadBrandData()
}
// MARK: Métodos
func setup(dados: Cabecalho) {
labelName.text = dados.name
labelLocation.text = dados.location
imageViewAvatar.image = UIImage(named: "1.png")
}
func loadBrandData() {
resultadoPesquisaViewModel?.loadBrandAPI(completion: { (sucess, error) in
if sucess {
DispatchQueue.main.async {
self.tableViewResult.reloadData()
}
}
})
}
}
// MARK: Extensions
extension ResultadoPesquisaViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let medicineDetails = UIStoryboard(name: "DetalhesMedicamentoViewController", bundle: nil).instantiateInitialViewController() as? DetalhesMedicamentoViewController {
//medicineDetails.setup(remedio: arrayMedice[indexPath.row])
navigationController?.pushViewController(medicineDetails, animated: true)
}
}
}
extension ResultadoPesquisaViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let allDrugs = resultadoPesquisaViewModel?.numberOfRows() {
return allDrugs
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NomeRemediosTableViewCell", for: indexPath) as! NomeRemediosTableViewCell
cell.setup(nameMedice: resultadoPesquisaViewModel!.arrayRemedios[indexPath.row].produto)
return cell
}
}
| true
|
2f9a49d907ea9dd61ee3dc87d000a79f6bf1ff08
|
Swift
|
xuhaili/Moots
|
/Examples/Thread/Thread_Swift2.3/GCDDemo-Swift/GCD.swift
|
UTF-8
| 12,433
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
//
// GCD.swift
// GCDDemo-Swift
//
// Created by Mr.LuDashi on 16/3/29.
// Copyright © 2016年 ZeluLi. All rights reserved.
//
import Foundation
/**
获取当前线程
- returns: NSThread
*/
func getCurrentThread() -> NSThread {
let currentThread = NSThread.currentThread()
return currentThread
}
/**
当前线程休眠
- parameter timer: 休眠时间/单位:s
*/
func currentThreadSleep(timer: NSTimeInterval) -> Void {
NSThread.sleepForTimeInterval(timer)
//或者使用
//sleep(UInt32(timer))
}
/**
获取主队列
- returns: dispatch_queue_t
*/
func getMainQueue() -> dispatch_queue_t {
return dispatch_get_main_queue();
}
/**
获取全局队列, 并指定优先级
- parameter priority: 优先级
DISPATCH_QUEUE_PRIORITY_HIGH 高
DISPATCH_QUEUE_PRIORITY_DEFAULT 默认
DISPATCH_QUEUE_PRIORITY_LOW 低
DISPATCH_QUEUE_PRIORITY_BACKGROUND 后台
- returns: 全局队列
*/
func getGlobalQueue(priority: dispatch_queue_priority_t = DISPATCH_QUEUE_PRIORITY_DEFAULT) -> dispatch_queue_t {
return dispatch_get_global_queue(priority, 0)
}
/**
创建并行队列
- parameter label: 并行队列的标记
- returns: 并行队列
*/
func getConcurrentQueue(label: String) -> dispatch_queue_t {
return dispatch_queue_create(label, DISPATCH_QUEUE_CONCURRENT)
}
/**
创建串行队列
- parameter label: 串行队列的标签
- returns: 串行队列
*/
func getSerialQueue(label: String) -> dispatch_queue_t {
return dispatch_queue_create(label, DISPATCH_QUEUE_SERIAL)
}
/**
使用dispatch_sync在当前线程中执行队列
- parameter queue: 队列
*/
func performQueuesUseSynchronization(queue: dispatch_queue_t) -> Void {
for i in 0..<3 {
dispatch_sync(queue) {
currentThreadSleep(1)
print("当前执行线程:\(getCurrentThread())")
print("执行\(i)")
}
print("\(i)执行完毕")
}
print("所有队列使用同步方式执行完毕")
}
/**
使用dispatch_async在当前线程中执行队列
- parameter queue: 队列
*/
func performQueuesUseAsynchronization(queue: dispatch_queue_t) -> Void {
//一个串行队列,用于同步执行
let serialQueue = getSerialQueue("serialQueue")
for i in 0..<3 {
dispatch_async(queue) {
currentThreadSleep(Double(arc4random()%3))
let currentThread = getCurrentThread()
dispatch_sync(serialQueue, { //同步锁
print("Sleep的线程\(currentThread)")
print("当前输出内容的线程\(getCurrentThread())")
print("执行\(i):\(queue)\n")
})
}
print("\(i)添加完毕\n")
}
print("使用异步方式添加队列")
}
/**
延迟执行
- parameter time: 延迟执行的时间
*/
func deferPerform(time: Double) -> Void {
//dispatch_time用于计算相对时间,当设备睡眠时,dispatch_time也就跟着睡眠了
let delayTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, getGlobalQueue()) {
print("执行线程:\(getCurrentThread())\ndispatch_time: 延迟\(time)秒执行\n")
}
//dispatch_walltime用于计算绝对时间,而dispatch_walltime是根据挂钟来计算的时间,即使设备睡眠了,他也不会睡眠。
let nowInterval = NSDate().timeIntervalSince1970
var nowStruct = timespec(tv_sec: Int(nowInterval), tv_nsec: 0)
let delayWalltime = dispatch_walltime(&nowStruct, Int64(time * Double(NSEC_PER_SEC)))
dispatch_after(delayWalltime, getGlobalQueue()) {
print("执行线程:\(getCurrentThread())\ndispatch_walltime: 延迟\(time)秒执行\n")
}
print(NSEC_PER_SEC) //一秒有多少纳秒
}
/**
全局队列的优先级关系
*/
func globalQueuePriority() {
//高 > 默认 > 低 > 后台
let queueHeight: dispatch_queue_t = getGlobalQueue(DISPATCH_QUEUE_PRIORITY_HIGH)
let queueDefault: dispatch_queue_t = getGlobalQueue(DISPATCH_QUEUE_PRIORITY_DEFAULT)
let queueLow: dispatch_queue_t = getGlobalQueue(DISPATCH_QUEUE_PRIORITY_LOW)
let queueBackground: dispatch_queue_t = getGlobalQueue(DISPATCH_QUEUE_PRIORITY_BACKGROUND)
//优先级不是绝对的,大体上会按这个优先级来执行。 一般都是使用默认(default)优先级
dispatch_async(queueLow) {
print("Low:\(getCurrentThread())")
}
dispatch_async(queueBackground) {
print("Background:\(getCurrentThread())")
}
dispatch_async(queueDefault) {
print("Default:\(getCurrentThread())")
}
dispatch_async(queueHeight) {
print("High:\(getCurrentThread())")
}
}
/**
给串行队列或者并行队列设置优先级
*/
func setCustomeQueuePriority() {
//优先级的执行顺序也不是绝对的
//给serialQueueHigh设定DISPATCH_QUEUE_PRIORITY_HIGH优先级
let serialQueueHigh = getSerialQueue("cn.zeluli.serial1")
dispatch_set_target_queue(serialQueueHigh, getGlobalQueue(DISPATCH_QUEUE_PRIORITY_HIGH))
let serialQueueLow = getSerialQueue("cn.zeluli.serial1")
dispatch_set_target_queue(serialQueueLow, getGlobalQueue(DISPATCH_QUEUE_PRIORITY_LOW))
dispatch_async(serialQueueLow) {
print("低:\(getCurrentThread())")
}
dispatch_async(serialQueueHigh) {
print("高:\(getCurrentThread())")
}
}
/**
一组队列执行完毕后在执行需要执行的东西,可以使用dispatch_group来执行队列
*/
func performGroupQueue() {
print("\n任务组自动管理:")
let concurrentQueue: dispatch_queue_t = getConcurrentQueue("cn.zeluli")
let group: dispatch_group_t = dispatch_group_create()
//将group与queue进行管理,并且自动执行
for i in 1...3 {
dispatch_group_async(group, concurrentQueue) {
currentThreadSleep(1)
print("任务\(i)执行完毕\n")
}
}
//队列组的都执行完毕后会进行通知
dispatch_group_notify(group, getMainQueue()) {
print("所有的任务组执行完毕!\n")
}
print("异步执行测试,不会阻塞当前线程")
}
/**
* 使用enter与leave手动管理group与queue
*/
func performGroupUseEnterAndleave() {
print("\n任务组手动管理:")
let concurrentQueue: dispatch_queue_t = getConcurrentQueue("cn.zeluli")
let group: dispatch_group_t = dispatch_group_create()
//将group与queue进行手动关联和管理,并且自动执行
for i in 1...3 {
dispatch_group_enter(group) //进入队列组
dispatch_async(concurrentQueue, {
currentThreadSleep(1)
print("任务\(i)执行完毕\n")
dispatch_group_leave(group) //离开队列组
})
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER) //阻塞当前线程,直到所有任务执行完毕
print("任务组执行完毕")
dispatch_group_notify(group, concurrentQueue) {
print("手动管理的队列执行OK")
}
}
//信号量同步锁
func useSemaphoreLock() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
//创建信号量
let semaphoreLock: dispatch_semaphore_t = dispatch_semaphore_create(1)
var testNumber = 0
for index in 1...10 {
dispatch_async(concurrentQueue, {
dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER) //上锁
testNumber += 1
currentThreadSleep(Double(1))
print(getCurrentThread())
print("第\(index)次执行: testNumber = \(testNumber)\n")
dispatch_semaphore_signal(semaphoreLock) //开锁
})
}
print("异步执行测试\n")
}
/**
循环执行
*/
func useDispatchApply() {
print("循环多次执行并行队列")
let concurrentQueue: dispatch_queue_t = getConcurrentQueue("cn.zeluli")
//会阻塞当前线程, 但concurrentQueue队列会在新的线程中执行
dispatch_apply(3, concurrentQueue) { (index) in
currentThreadSleep(Double(index))
print("第\(index)次执行,\n\(getCurrentThread())\n")
}
print("\n\n循环多次执行串行队列")
let serialQueue: dispatch_queue_t = getSerialQueue("cn.zeluli")
//会阻塞当前线程, serialQueue队列在当前线程中执行
dispatch_apply(3, serialQueue) { (index) in
currentThreadSleep(Double(index))
print("第\(index)次执行,\n\(getCurrentThread())\n")
}
}
//暂停和重启队列
func queueSuspendAndResume() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
dispatch_suspend(concurrentQueue) //将队列进行挂起
dispatch_async(concurrentQueue) {
print("任务执行")
}
currentThreadSleep(2)
dispatch_resume(concurrentQueue) //将挂起的队列进行唤醒
}
/**
使用给队列加栅栏
*/
func useBarrierAsync() {
let concurrentQueue: dispatch_queue_t = getConcurrentQueue("cn.zeluli")
for i in 0...3 {
dispatch_async(concurrentQueue) {
currentThreadSleep(Double(i))
print("第一批:\(i)\(getCurrentThread())")
}
}
dispatch_barrier_async(concurrentQueue) {
print("\n第一批执行完毕后才会执行第二批\n\(getCurrentThread())\n")
}
for i in 0...3 {
dispatch_async(concurrentQueue) {
currentThreadSleep(Double(i))
print("第二批:\(i)\(getCurrentThread())")
}
}
print("异步执行测试\n")
}
/**
以加法运算的方式合并数据
*/
func useDispatchSourceAdd() {
var sum = 0 //手动计数的sum, 来模拟记录merge的数据
let queue = getGlobalQueue()
//创建source
let dispatchSource:dispatch_source_t = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, queue)
dispatch_source_set_event_handler(dispatchSource) {
print("source中所有的数相加的和等于\(dispatch_source_get_data(dispatchSource))")
print("sum = \(sum)\n")
sum = 0
currentThreadSleep(0.3)
}
dispatch_resume(dispatchSource)
for i in 1...10 {
sum += i
print(i)
dispatch_source_merge_data(dispatchSource, UInt(i))
currentThreadSleep(0.1)
}
}
/**
以或运算的方式合并数据
*/
func useDispatchSourceOr() {
var or = 0 //手动计数的sum, 来记录merge的数据
let queue = getGlobalQueue()
//创建source
let dispatchSource:dispatch_source_t = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_OR, 0, 0, queue)
dispatch_source_set_event_handler(dispatchSource) {
print("source中所有的数相加的和等于\(dispatch_source_get_data(dispatchSource))")
print("or = \(or)\n")
or = 0
currentThreadSleep(0.3)
}
dispatch_resume(dispatchSource)
for i in 1...10 {
or |= i
print(i)
dispatch_source_merge_data(dispatchSource, UInt(i))
currentThreadSleep(0.1)
}
print("\nsum = \(or)")
}
/**
使用dispatch_source创建定时器
*/
func useDispatchSourceTimer() {
let queue: dispatch_queue_t = getGlobalQueue()
let source: dispatch_source_t = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
//设置间隔时间,从当前时间开始,允许偏差0纳秒
dispatch_source_set_timer(source, DISPATCH_TIME_NOW, UInt64(1 * NSEC_PER_SEC), 0)
var timeout = 10 //倒计时时间
//设置要处理的事件, 在我们上面创建的queue队列中进行执行
dispatch_source_set_event_handler(source) {
print(getCurrentThread())
if(timeout <= 0) {
dispatch_source_cancel(source)
} else {
print("\(timeout)s")
timeout -= 1
}
}
//倒计时结束的事件
dispatch_source_set_cancel_handler(source) {
print("倒计时结束")
}
dispatch_resume(source)
}
| true
|
2df8b6db44bcef2505d720cb22dda206b4a2ec0b
|
Swift
|
Rezki-Pratama/submission_katalog
|
/submission_katalog/View/Handler/FormatValue.swift
|
UTF-8
| 230
| 3.109375
| 3
|
[] |
no_license
|
import Foundation
extension Float {
func formatFloat() -> String {
return String(format: "%.2f",self)
}
}
extension Double {
func formatDouble() -> String {
return String(format: "%.2f",self)
}
}
| true
|
af03328fbb5abe1894afe9269995b6cb8112c11d
|
Swift
|
drapon/tepcoAPI
|
/createTodo/ViewController.swift
|
UTF-8
| 2,840
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// createTodo
//
// Created by Ryuichi Hayashi on 2014/07/26.
// Copyright (c) 2014年 Ryuichi Hayashi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIApplicationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ja")
//書式を整える
dateFormatter.dateFormat = "yyyy/MM/dd/HH"
//データをフォーマット
let d = dateFormatter.stringFromDate(date)
let origin:NSString = "http://tepco-usage-api.appspot.com/"
let origin_url = origin + d + ".json"
let url = NSURL(string: origin_url)
let request = NSURLRequest(URL: url)
let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
let dictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: nil) as NSDictionary
func JSONStringify(jsonObj: AnyObject) -> String {
var e: NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(
jsonObj,
options: NSJSONWritingOptions(0),
error: &e)
if e {
return ""
} else {
return NSString(data: jsonData, encoding: NSUTF8StringEncoding)
}
}
//Capacity
var capaLabel = UILabel(frame : CGRectMake(20, 200, 300, 20))
for (tepcoCode, tepcoName) in dictionary {
if(tepcoCode as NSString == "capacity"){
capaLabel.text = "最大値: \(tepcoName)"
var capaTepco = "\(tepcoName)"
}
}
self.view.addSubview(capaLabel)
//forecast_peak_usage
var peakLabel = UILabel(frame : CGRectMake(20, 200, 300, 100))
for (tepcoCode, tepcoName) in dictionary {
if(tepcoCode as NSString == "forecast_peak_usage"){
peakLabel.text = "利用電力: \(tepcoName)"
let usedTepco = "\(tepcoName)"
}
}
self.view.addSubview(peakLabel)
//残り
// var zanLabel = UILabel(frame : CGRectMake(20, 200, 300, 180))
// zanLabel.text = "aaaa"
// self.view.addSubview(zanLabel)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
56cd62c29d8f59420e5d2c0f311ac146022c7306
|
Swift
|
rioishii/simplecalc
|
/SimpleCalc/SimpleCalc/main.swift
|
UTF-8
| 1,774
| 3.4375
| 3
|
[] |
no_license
|
//
// main.swift
// SimpleCalc
//
// Created by Ted Neward on 10/3/17.
// Copyright © 2017 Neward & Associates. All rights reserved.
//
import Foundation
public class Calculator {
public func calculate(_ args: [String]) -> Int {
if args.count < 2 {
return 0;
}
switch args.last {
case "count":
return args.count - 1
case "avg":
var sum = 0
let numbers = args.dropLast()
for num in numbers {
sum += Int(num)!
}
return sum / (numbers.count)
case "fact":
var fact = 1
for i in 1...Int(args[0])! {
fact *= i
}
return fact
default:
switch args[1] {
case "+":
return Int(args[0])! + Int(args[2])!
case "-":
return Int(args[0])! - Int(args[2])!
case "*":
return Int(args[0])! * Int(args[2])!
case "/":
return Int(args[0])! / Int(args[2])!
case "%":
return Int(args[0])! % Int(args[2])!
default:
return Int(args[0])!
}
}
}
public func calculate(_ arg: String) -> Int {
return calculate( arg.split(separator: " ").map({ substr in String(substr) }) )
}
}
let cmdLine = CommandLine.arguments
switch cmdLine.count {
case 1:
print("UW Calculator v1")
print("Enter an expression separated by returns:")
let first = readLine()!
let operation = readLine()!
let second = readLine()!
print(Calculator().calculate([first, operation, second]))
default:
print(Calculator().calculate(Array(cmdLine.dropFirst())))
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.