Posts

Things to consider when designing the user interface

Consider the whole user experience. Plan it step by step. Have a prominent search widget and a prominent filter widget. If something is unavailable, rather than taking it away and letting the user guess about whether or not it will be available, list it, indicate it is out of stock and let the user have the option of being alerted once it is in stock. If there is a location feature, allow the user to change location if necessary.  Allow users to clear filter and close panels easily. Give custom suggestions for search and let users view recent search Think of how to make the search experience better.  Ensure that the user has less need to remember things. Think about the questions that your user might need to answer to make a decision and help to provide it. Allow for comparison of products and allow users to bookmark things. Make editing easy. As the user keys in, the screen should scroll down to reveal the next box. Ask for permission only when needed, not at the...

Get calories burnt from healthkit information

1. Go to symbols navigator, capabilities and switch on HealthKit. 2. Go to developer.apple.com, create an app ID with your correct bundle id gotten from your app. Indicate that it is an explicit app id and include healthkit in it. 3. Create a provisioning profile - App development - using the new app id created and download it. 4. Open xcode and import profile (sign-in profile). Select the provisioning profile you have just created. 5. Choose the new app id that you have just created. 6. Add the following to info.plist: Privacy – Health Share Usage Description Privacy – Health Update Usage Description 7. In the xcode swift file, import HealthKit This code reads calories burnt and returns true or false depending on whether you are able to be authorised to read the data

Edit constraints for a UI element

Click on the constraints at the side with the mousepad until it is in editing mode. Edit the constraint and press enter.

Asking someone to review your app

You can follow the instructions listed here.

Sharing on Social Media

First, when your app is completed, go to iTunes connect and create a new app. Key in the needed info (remember that your bundle id and sku starts with com.... the one that you use to uniquely identify your app). Go to the bottom and the page and look for 'View your app in App Store'. Click on it to get the URL of your app. Add a button and add an onclick event with the following code: let textToShare = "Join me in getting fit through dance!"                  if let myWebsite = NSURL (string: "https://itunes.apple.com/us/app/daily-dance-fitness/id1372552926?ls=1&mt=8" ) {             let objectsToShare = [textToShare, myWebsite] as [ Any ]             let activityVC = UIActivityViewController (activityItems: objectsToShare, applicationActivities: nil )              activityVC. excludedActivityTypes = [ UIActivityType . airD...

How to add admob to your app

First download cocaopods: https://cocoapods.org/app 1. Go to admob and sign up/sign in 2. Click on apps -> IOS 3. Follow instructions 4. Get your admob id Then go to your project folder in desktop in terminal: cd Desktop/nameOfFolder Type: pod init Enter Next, open your pod file inside it, in the target, add: pod 'Google-Mobile-Ads-SDK' Press install When it has been installed, go to terminal and type: pod install --repo-update Next, open your Xcode project and go to the AppDelegate file: import GoogleMobileAds In the application function add: (func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool ) GADMobileAds.configure(withApplicationID: "YOUR_ADMOB_APP_ID") Inside your app itself:   var interstitial: GADInterstitial! //in viewDidLoad:   interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/441146...

Playing or pausing a video in web view

webview.evaluateJavaScript("ytplayer.playVideo()") webview.evaluateJavaScript("ytplayer.pauseVideo()") webview.evaluateJavaScript("ytplayer.stopVideo()")

Countdown timer

Create a variable Timer: var timer = Timer() var timeSet = 60 //this means the timer is for 60 seconds Create 2 functions:     @objc func updateTimer() {         self . timeSet -= 1     //This will decrement(count down)the seconds.         if ( self . timeSet == 0 )         {             self . dancewv . reload ()             continuePlaying ()         }     }   func runTimer() {         timer = Timer . scheduledTimer (timeInterval: 1 , target: self ,   selector: ( #selector ( updateTimer )), userInfo: nil , repeats: true )              } In the function where you need the timer to run, call runTimer()

Stop a queue

Above ViewDidLoad: private var workItem: DispatchWorkItem? In ViewDidLoad or where the queue shows: workItem = DispatchWorkItem {                 //actions in the queue                      }         DispatchQueue . main . asyncAfter (deadline: . now (), execute: workItem !) In ViewDidDisappear //if loading web view self.nameOfWebView . stopLoading ()         workItem ?. cancel ()

Starting a new project?

After planning it on paper, Go to Xcode and create a new project, single page. Click on the storyboard on the left side of the screen.  Turn that single page into a navigation page with links. Embed it in a view controller (Editor - embed in Navigation Controller). (see this for details) Set the navigation controller as the initial view controller. You can edit the main title and the colour of the navigation bar using the main navigation controller attribute inspector. Add a bar button link at the top of home page with the words 'HOME'. The other pages will be populated with the back button. Add other view controllers by drag and dropping it back to the screen. Add the UI elements for these view controllers and add missing constraints. Click and drag from the button in the main navigation page to the view controllers they link to. For each view controllers added, go to file->new. Create new Cocoa Touch file for each view controller and give it a name. Click on...

Swift Basics: Formatting guide

Do not use semi-colons. Do not use () for if else statement - if x < 5 {} instead of if (x<5){} Types should always start with a capital letter. They should not have underscore. MyClass Functions and methods should be named in camel case. Constants and variables should be named in camel case. Use the default indentations given. Add an extra blank line between functions and methods.  Use triple /// in block comments for functions.  Use double // in comments for inline comments.  Define everything as a constant first, then change it to a variable when you have to change it.  Only use optional types when necessary. Avoid forced unwrapping. Use optional binding instead. Use type inference: instead of var a: Int = 1, use var a = 1 Use shorthand declarations for collections: var myArray: [String] = [] instead of var myArray: Array<String> Use switch case instead of multiple if statements.

Swift Basics: Concurrency and Parallelism - running multiple tasks

Concurrency - many tasks starting, running, and completing at the same time period. Parallelism - 2 or more tasks running simultaneously. If we have a 4-core processor, we can run 4 tasks simultaneously. Asynchronous functions are functions that run in the background. These functions might take a long time to complete. It starts with the long task running and comes back before the task's completion. To have asynchronous running of tasks, we can make use of GCD and operation queues. GCD stands for Grand Central Dispatch. There are three types of queues that it uses. Serial queue - executed in the order in which they are submitted. No two tasks will run simultaneously. Concurrent queue - execute concurrently, but start according to the time they are added to the queue. Main dispatch queues - main thread. With dispatch queues, threads are managed efficiently and we can control the order in which they start. Let's say I have a function called Countdown(timing: Int). ...

Swift Basics: Mix and Match

Mix and Match is when you want to combine other codes with Swift programming. For instance, using objective C with swift programming. You can find more details here.

Swift Basics: Closures

Closures are when you add functions, etc, blocks of code to a variable declaration. It can take in parameters and can have return values. Here is a simple closure: let c1 = { (name: String) -> Void in print(name) } To execute it: c1("ABC") They are self contained blocks of code. They can be used throughout the application code. We can indicate that a closure is a parameter in a function. func test(handler: (String) -> Void) { //(String) -> Void means that it is a closure that takes in a String and does not have a return value   handler("efg") } Then when we call the function: test(handler: c1) With a return value: let c2 = {   (name: String) -> String in   return "Well \(name)" } to call it: var message = c2("Mary") Let's say we have a function that accepts a closure as a parameter: func test(handler:() -> Void) {   handler() } create a closure: let c3 = { ()-> Void in print("ABC...

Swift Basics - Generics

We use generics when we need to create functions that can be used with multiple types. If I wish to create a function that swaps 2 objects, I will need to create a function for each type, without generics: func swapInt(a: Int, b: Int){} func swapString(a: String, b: String){} func swapDouble(a: Double, b: Double){} We can condense all 3 into one function that makes use of a generic type: func swap<T>(a: T, b: T){} T is the generic type assigned. You can also choose another name for T: func swap<XYZ>(a: XYZ, b: XYZ) If there are multiple types, we can use different name placeholders for the types: func swap<T, E>(a: T, b: E){} To call the function: var a = 5 var b = 10 swap(a: &a, b: &b) //placing & before a and b just ensures that their values get updated and persists outside of the function A generic type is a class, structure or enumeration that can work with any type. We can create a class of a generic type: class Listing<G>{  var items = [G](...

Swift Basics - subscripts

Shortcuts to access elements in collections, lists or sequences. Subscript of an array: var array1 = [1, 2, 3, 4, 5, 6] print(array1[2]) Custom subscripts: class MyFoods {  private var foods = ["Ice cream", "Pizza", "Hot dog"]  subscript(index: Int) -> String  {  get { return names[index]}  set { names[index] = newValue} } To use it: var myFoods = MyFoods() print(myFoods[0]) Ready only custom subscripts: class MyFoods {  private var foods = ["Ice cream", "Pizza", "Hot dog"]  subscript(index: Int) -> String  {  get { return names[index]} } OR class MyFoods {  private var foods = ["Ice cream", "Pizza", "Hot dog"]  subscript(index: Int) -> String  {   return names[index] } You can calculate something inside a subscript: struct AreaOfTable {  var length: Int  subscript(index: Int) -> Int  { return length * Index} } To use: var myTable = AreaOfTable(length: 3) print(myTable[3]) A subscript ...

Swift basics - Extensions

Extensions: When you need to edit a type like string without overriding existing functionality: extension String {   var firstLetter: Characters?{ get return self.characters.first}}  func reverse() -> String{//... } } To call it: var myString = "ABC" print(myString.firstLetter)

Swift basics - classes and structures

Classes and structures Classes and structures have properties, methods, initialisers, subscripts (provide access to values), and extensions. Difference between classes and structures: A class can inherit from parent classes, a structure is unable to. Structures can implement protocols, though. Structures do not have custom deinitialisers, classes do. If a class object gets sent to a a function, changes to the object will persist. However, changes to the structure will not persist. Structures or classes? Structures make use of less memory overheads, so there are performance gains in using them. To create a class: class MyClass {    //properties    let a = 3    //or let a: Int    var b = "" } Create a structure: struct MyStruct{    //properties    let a = 3    var b = "" } You can able to create an instance of a class and of a structure: var aStruct = MyStruct() var aClass = MyClass() By default, you can give the proper...

Swift basics - functions

Defining a function with parameters and return types: func hello(name: String) -> Void{} //the above does not have a return value func hello(name: String) -> String { let ret = "Hello " + name return ret} To call the above function: let msg = hello(name: "Mary") //I am aware of the return value but don't want to use it: _ = hello(name: "Mary") You can also do this: @discardableResult func hello(name: String) -> String { let ret = "Hello " + name return ret } Multi-parameter functions: func hello(name: String, greeting: String) { } To call: hello(name:"Mary", greeting:"Whats up") You can define a parameter with default values. func hello(name: String, greeting: String = "Whats up"){} When calling, you can either call with the greeting or without it: hello(name: "Mary") hello(name:"Mary", greeting:"Good day") We can also declare multiple default values: func hello(name: String...

Swift Basics - filtering

Filtering with the where statement: for number in 1...50 where number % 3 == 0 { } //get numbers from 1 to 50 that can be divided by 3 without remainder Filtering using for case: var pupilsWhoWon = [("Mary", 10), ("John", 50), ("Mary", 80)] for case let ("Mary", score) in pupilsWhoWon { print(score)} Filter out nil values: let myNum: [Int?] = [1, 2, nil, 3, nil] for case let .some(num) in myNum {   print(num) } //each optional value is an enumeration with either case none or some. If there is a value, it would have case some. You can filter out the numbers that have a value are are more than 3: for case let num? in myNum where num > 3 {} You can use if case statements for enumerations: enum Book{ case Title(String) case Edition(Int) case Author(String) } var thisBook = Book.Edition(2) if case let .Edition(num) = thisBook {print("This book's edition is \(num)")} OR if case let .Edition(num) = thisBook, num == 2 {} //Checks to see ...