Last active
February 22, 2023 19:13
-
-
Save sejas/8648ca73421e83084afd to your computer and use it in GitHub Desktop.
SWIFT GISTs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Swift useful and common gists |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(UIApplication.sharedApplication().delegate as! AppDelegate) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Hide Statusbar | |
override func prefersStatusBarHidden() -> Bool { | |
return true | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
override func viewWillAppear(animated: Bool) { | |
super.viewWillAppear(animated) | |
//Suscribe Notification | |
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) | |
} | |
override func viewWillDisappear(animated: Bool) { | |
super.viewWillDisappear(animated) | |
//Unsuscribe Notification | |
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) | |
} | |
func getKeyboardHeight(notification: NSNotification) -> CGFloat{ | |
let userInfo = notification.userInfo | |
//of CGRect | |
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue | |
return keyboardSize.CGRectValue().height | |
} | |
func keyboardWillShow(notification: NSNotification){ | |
view.frame.origin.y -= getKeyboardHeight(notification) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getImage(){ | |
//https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/ | |
let imageUrl = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_November_2010-1a.jpg")! | |
let task = NSURLSession.sharedSession().dataTaskWithURL(imageUrl) { (data, response, error) in | |
if nil == error { | |
let downloadedImage = UIImage(data: data!) | |
performUIUpdatesOnMain({ | |
self.imageView.image = downloadedImage | |
}) | |
}else{ | |
print("error",error) | |
} | |
} | |
//It starts the request | |
task.resume() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getJson(){ | |
let url = NSURL(string: "https://somjsonurl.com")! | |
let request = NSURLRequest(URL: url) | |
//We can change the method (GET/POST) using NSMutableURLRequest | |
let task = session.dataTaskWithRequest(request) { (data, response, error) in | |
// if an error occurs, print it and re-enable the UI | |
func displayError(error: String) { | |
print(error) | |
performUIUpdatesOnMain { | |
self.setUIEnabled(true) | |
self.photoTitleLabel.text = "No photo returned. Try again." | |
self.photoImageView.image = nil | |
} | |
} | |
/* GUARD: Was there an error? */ | |
guard (error == nil) else { | |
displayError("There was an error with your request: \(error)") | |
return | |
} | |
/* GUARD: Did we get a successful 2XX response? */ | |
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else { | |
displayError("Your request returned a status code other than 2xx!") | |
return | |
} | |
/* GUARD: Was there any data returned? */ | |
guard let data = data else { | |
displayError("No data was returned by the request!") | |
return | |
} | |
// parse the data | |
let parsedResult: AnyObject! | |
do { | |
parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) | |
} catch { | |
displayError("Could not parse the data as JSON: '\(data)'") | |
return | |
} | |
guard let stat = parsedResult["someKey"] as? String where stat == "ok" else { | |
displayError("API ERROR \(parsedResult)") | |
return | |
} | |
} | |
//It starts the request | |
task.resume() | |
} | |
//AUX | |
//Create safe URLS | |
func urlFromParameters(parameters: [String:AnyObject]) -> NSURL { | |
let components = NSURLComponents() | |
components.scheme = Constants.APIScheme | |
components.host = Constants.APIHost | |
components.path = Constants.APIPath | |
components.queryItems = [NSURLQueryItem]() | |
for (key, value) in parameters { | |
let queryItem = NSURLQueryItem(name: key, value: "\(value)") | |
components.queryItems!.append(queryItem) | |
} | |
return components.URL! | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func saveAValue() { | |
let defaults = NSUserDefaults.standardUserDefaults() | |
// Save a float value into the defaults, using the key "myValue" | |
defaults.setFloat(22.5, forKey: "myValue") | |
} | |
func readAValue() { | |
// Read the current value for the "myValue" key | |
let defaults = NSUserDefaults.standardUserDefaults() | |
theValue = defaults.floatForKey("myValue") | |
... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
//Select Image | |
@IBAction func actionPicker(sender: AnyObject) { | |
let nextController = UIImagePickerController() | |
presentViewController(nextController, animated: true, completion: nil) | |
} | |
//Share | |
@IBAction func actionActivity(sender: AnyObject) { | |
let image = UIImage() | |
let nextController = UIActivityViewController(activityItems: [image], applicationActivities: nil) | |
presentViewController(nextController, animated: true, completion: nil) | |
} | |
//Show alert | |
@IBAction func actionAlert(sender: AnyObject) { | |
let nextController = UIAlertController() | |
let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.Default){ action in | |
self.dismissViewControllerAnimated(true, completion: nil) | |
} | |
nextController.addAction(okAction) | |
presentViewController(nextController, animated: true, completion: nil) | |
} | |
//Custom View Controller | |
@IBAction func showCustomView() { | |
var controller: CustomViewController | |
controller = self.storyboard?.instantiateViewControllerWithIdentifier("CustomViewControllerIdentifier") as! CustomViewController | |
presentViewController(controller, animated: true, completion: nil) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var refreshControl: UIRefreshControl! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
refreshControl = UIRefreshControl() | |
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") | |
refreshControl.addTarget(self, action: Selector("refreshTable:"), forControlEvents: UIControlEvents.ValueChanged) | |
tableView.addSubview(refreshControl) | |
} | |
func refreshTable(sender:AnyObject) { | |
// refresh table | |
} | |
//end refreshing after | |
//refreshControl.endRefreshing() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Don't forget set the | |
@IBOutlet weak var collection: UICollectionView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
//It can be setted in the StoryBoard | |
collection.dataSource = self | |
collection.delegate = self | |
} | |
//MARK: Collection | |
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | |
return array.count | |
} | |
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { | |
let cell = collection.dequeueReusableCellWithReuseIdentifier("someCollectionCell", forIndexPath: indexPath) as! CollectionMemeCollectionViewCell | |
cell.imgView.image = array[indexPath.row].img | |
return cell | |
} | |
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { | |
collection.deselectItemAtIndexPath(indexPath, animated: true) | |
//PerformSegue? | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Set The size for each collection view cell | |
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
initFlowLayout() | |
} | |
func initFlowLayout() { | |
let space:CGFloat = 3.0 | |
let dimension = (self.view.frame.size.width - ( 2 * space )) / 3.0 | |
flowLayout.minimumInteritemSpacing = space | |
flowLayout.minimumLineSpacing = space | |
flowLayout.itemSize = CGSizeMake(dimension, dimension*1.5) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//MARK: Gestures | |
func gestureRecognizer(_: UIGestureRecognizer, | |
shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool { | |
return true | |
} | |
@IBAction func actionGesturePinch(sender: UIPinchGestureRecognizer) { | |
if let view = sender.view { | |
view.transform = CGAffineTransformScale(view.transform, | |
sender.scale, sender.scale) | |
sender.scale = 1 | |
} | |
} | |
@IBAction func actionGestureRotate(sender : UIRotationGestureRecognizer) { | |
if let view = sender.view { | |
view.transform = CGAffineTransformRotate(view.transform, sender.rotation) | |
sender.rotation = 0 | |
} | |
} | |
func resetScaleAndRotation(){ | |
imgChoosed.transform = CGAffineTransformScale(view.transform, | |
1, 1) | |
imgChoosed.transform = CGAffineTransformRotate(view.transform, 0) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UIImagePickerController *picker = [[UIImagePickerController alloc] init]; | |
picker.delegate = self; | |
picker.allowsEditing = NO; | |
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; | |
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{ | |
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage]; | |
self.imageView.image = chosenImage; | |
[picker dismissViewControllerAnimated:YES completion:nil]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment