Professional Documents
Culture Documents
Zusammenfassung iOSDev
Zusammenfassung iOSDev
Zusammenfassung iOSDev
Zusammenfassung
Functions
- Functions are full etched citizens
- May be returned by functions
- May be passes as parameter to functions
Closures
- Superset of functions
- Do not require a name
- Can access all elements of enclosing scope (variables, …)
Example:
Classes vs Structs
- Very similar concepts in Swift, they support
- Properties
- Methods
- Initializers
- …
- But
- Classes are passed by reference while structures are passed by value
- Structures do not support inheritance
- Structures do not support dynamic type checking
- Structures do not support de-initializers
- An object of a class may be shared by multiple references
Seite 1 von 26
fl
Protocols & Extensions
- Protocol
- Similiar to an interface in other languages
- Extensions
- Extends existing elements with new functionality
- Can extend classes, structs, simple datatypes, …
- Can be used to add protocol conformance to existing classes
- Cannot add additional storage
Error Handling
- Errors are normally de ned as an enum:
- A method can only throw an Error, If it is de ned as throws
- An Error can be raised using the throw clause
Seite 2 von 26
fi
fi
iOS Architecture
- iOS = Mobile OS from Apple for
- iPhone
- iPad
- iPod touch
- Based on macOS
- Unix based
- Kernel (Mach kernel)
- Base libraries
- UI library (Cocoa Touch) based on macOS UI
library (Cocoa)
Cocoa Touch
- Most important framework is the UIKit framework
- Basic app management
- User interface management
- View controller model
- Standard system views and controls
- Support for touch- and motion-based events
- Multitasking support
- Support for text and web content
- Cut, copy and paste support
- Animation support
- Support for Apple Push Noti cation service
- Local noti cation scheduling and delivery
- Support for sharing content through email, Twitter, Facebook, …
- Device-speci c features:
- Built-In camera (where present)
- The user’s photo library
- Device name and model information
- Battery state information
- Proximity sensor information
- Remote control information from attached headsets
- …
Seite 3 von 26
ff
fi
fi
fi
fi
fi
Media Layer
- Graphics technologies
- OpenGL ES framework
- Metal framework
- Audio technologies
- High level frameworks (player functionality)
- Low level frameworks (more sophisticated APIs)
- Video technologies
- Supports di erent abstraction levels
- AirPlay
- Stream audio and video to Apple TV or third party speakers
- Gaming technologies
- SceneKit framework
- SpriteKit framework
- Game controller framework
Seite 4 von 26
ff
Core OS Layer
- Kernel
- Based on mach kernel
- Manages:
- Virtual memory
- Thread
- File system
- Network
- IPC
- Drivers
- Interface between hardware and system frameworks
- Low-level UNIX interfaces
- Restricted access for security reasons!
- Contains libraries for
- Concurrency
- Networking
- File-system access
- Standard I/O
- Bonjour and DNS services
- Locale information
- Memory allocation
- Math computations
Multiple Dialogs
- Each dialog is implemented with its own MVC
- A UINavigationCtroller controller is used to transition between MVC
- Use a segue to transition from one MVC to another
- Show segue for normal navigation
- ShowDetail segue for master detail navigation
- Segue can be triggered directly from elements (storyboard) or from code
SwiftUI
- new Layer for iOS, macOS
- Uses declarative Swift syntax
- Combines view and view logic into a single le
- MVC pattern no longer used
- Instead: Separation of Concerns
- A view is understood as function of its state
- Views are implemented as Swift structs
- Value types
- Very light-weight implementation
- E ciently supports deep and wide view hierarchies
- Use modi ers to customize views ( „.padding“ for example)
Multiple Dialogs
- Based on NavigationView container
- Responsible for managing the navigation stack & bar
- View modi er .navigationBarTitle(…) can be used to set page title
- NavigationLink used to specify destination of the navigation and to display navigation element
Data handling
- Concept single source of truth
- Data is not duplicated between views anymore, but shared
- Dynamic data
- Can automatically handled by the View lifecycle, using @State properties
- Static data
- Is stored in standard properties
- And passed using the initializer
Seite 6 von 26
ffi
fi
fi
fi
Data Flow
Application Lifecycle
- Not running
- App has not been yet launched or
was terminated by the system
- Inactive
- App is running but does not
receive events
- May execute code
- Normally brief, transitional state
- Active
- Normal state for foreground apps
- Receiving input events
- Background
- App is executing code in the
background
- Normally brief, transitional state
- App may register for extra time in
this state
- Suspend
- App is in background no code is
executed
- App is still in memory
Application Delegate
- Application delegate is informed before the most of these state change:
- Delegate pattern
- App can therefor react appropriately
Seite 7 von 26
ScenePhase in SwiftUI
- Indicates the scene operational state
- Three possible states:
- Active
- Inactive
- Background
- Can be used to tie code execution to operational state
- Cleanup, when entering background for example
Controller Lifecycle
- Additionally to the application state, each controller has its own state
- Controller class will be informed by calling the appropriate methods
- Additional lifecycle method:
- viewDidLoad
Reference Counting
- iOS does not use a garbage collector but reference counting
- Reference count (retain count)
- Each new reference increases the count by one
- Each un-assignment of a reference decreases it by one
- When count reaches 0 object is deallocated
- Comparable to C++ std::shared_ptr and std::weak_ptr
- Problem: Reference cycle!
Seite 8 von 26
Automatic Reference Counting (ARC)
- Swift uses automatic reference counting (ARC)
- Handled automatically
- No code for allocating and releasing of objects required
- Keyword strong and weak to identify the pointer type when creating properties
Background Execution
1. ) Background Threading
Seite 9 von 26
Swift UI Data Flow
External Data
- State can be bound ($property) to @Binding properties
- Output value of a sub view
- Data can automatically publish changes (@Published) from ObservableObjects
- Can either be forwarded between views using bindings, or
- Data must be declared as @StateObject/@ObservedObject
- Automatically available to all views using the environment
- Accessed using @EnvironmentObject
- Must be initialized upstream in the view hierarchy using .environmentObject(…)
- UI will automatically update to changes
Seite 10 von 26
fi
fi
fi
Data Management
- Who owns the data?
- Life data to a common ancestor
- Use StateObject
- Consider placing global data in App
- Where to put the data?
- App -> App wide data
- Scene -> To the „window“, two open instances on iPad -> Each window has own state
- View -> Only current view has the data
ObservableObject
- Protocol
- Only available for classes
- Part of the model
- Exporting data to the view
- Glue logic between data model and view
Web Access
Seite 11 von 26
HTTP Connection in iOS
- Use URLSession.shared.dataTask(with: url) {…} for creating an async task for loading data
- Pass a closure to the task:
- Executed on background thread
- {data, response, error in … }
- Process the result or the error in the closure
- Start the task with task.resume()
- Update the UI when loading has nished
- Caution: Closure is on the background thread
- Recall dispatching back to MainThread!
HTTP/HTTPS
- Only https is supported by iOS
- HTTP connections are prohibited
- But can be activated temporarily (mostly for development)
- Entry in Info.plist of the app
- Accept into the AppStore only
- If su ciently justi ed and
- Privacy concerns are cleared
- HTTP connections to localhost (the phone itself) are allowed
- For development: Running webserver on the Mac is accessible
Seite 12 von 26
ffi
fi
fi
fl
fi
Lists: Overview
- Display a structured and scrollable list of items
- UIKit vs SwiftUI
- UIKit: UITableView (Imperative)
- SwiftUI: List (Declarative)
- To display items in more than one dimension use Collection view (UIKit) or Grid (SwiftUI)
UIKit (imperative way):
- De ne what data to display
- Add table view
- Add cells to table view
- Add elements and constraints to cell
- Connect outlets
- Register cells
- Implement and connect delegates
SwiftUI (declarative way):
- De ne the data and declare what you want to display
UITableView (UIKit)
- Compared to SwiftUI more complex to use and get familiar with
- Construction
- Each list contains one or more sections
- Each section contains one or more rows
- A row represents an item
Seite 13 von 26
fi
fi
fi
FileSystem
- Create, read and write les and folders in the le system
- FileManager is a high-level API to access Apple File System
- Possible usages
- Save photos/ les temp for uploading
- Store les for the user
FileSystem: FileManager
- Use the method url(for: …, in …, appropriateFor: …, create: …) to request appropriate directory
- Set for: to documentDirectory for user created les
- Append le name to the URL
- Example:
- Let leManager = FileManager.default
- Let documetDir = try leManager.url(for . docDirectory, in: .userDomainMask, appropriateFor:
nil, create:false)
- Several formats possible:
- Plain text, custom binary format, json encoding/decoding
Dependency Management
- Swift Package Manager by Apple
- Create or include package dependencies
- Integrated in Xcode
- Usage:
- Share code between your projects
- Integrate third-party code into your project
- Alternative solutions from third-parties:
- Carthage
- CocoaPods
SwiftPackageManager:
PropertyWrappers
- Encapsulates code for typical usage patterns
- We already know:
- @State
- @Published
- @EnvironmentObject
- …
- Support for custom wrappers
- Creates 2 properties
- The wrapper itself: $name
- Access property to the contents: name
Seite 14 von 26
fi
fi
fi
fi
fi
fi
fi
fi
fi
Combine Framework
- Declarative framework for processing values over time
- 3 key concepts:
- Publisher: publishes values
- Subscriber: subscribes to value updates
- Operatores: react on upstream publisher values and republish them
- Prede nes publisher for many async Swift interfaces:
- URLSession
- Noti cationCenter
- …
Concept
Protocol De nition
Timing
Seite 15 von 26
fi
fi
fi
Can be implemented directly and using chained syntax
Cancellable
- Operations can canceled
- By calling cancel on the cancellable
- If the cancellable gets out of scope (is destroyed)
- Long running task which are no longer required are therefore canceled automatically
- For example: if view is no longer used and destroyed
Additional Operators
FailureHandling
- Several options to handle failure states using di erent operators
- Examples:
- assertNoFailure
- Catch
- atMap - may use catch for erroneous tokens, but continues to listen to upstream
UserDefaults
- Application settings can be stored within user defaults database
- Key/value pair store
- Supported by the class UserDefaults
- Supports multiple datatypes
- String
Seite 16 von 26
fl
ff
- Integer
- Bool
- Array
- Dictionary
- …
- Reading a value:
- Let myBool = UserDefaults.standard.bool(forKey: „key1“)
- Let myString = UserDefaults.standard.String(forKey: „key2“)
- Setting a value:
- UserDefaults.standard.set(false, forKey: „key1“)
- Setting default values
- UserDefaults.standard.register(defaults: [„key1“ : false, „key2“: „Hello World“])
- Defaults are not persisted
- Must be set on each app launch
UserDefaults: UI
- iOS uses a system wide settings dialog
- App settings can be con gured using a settings bundle
- All settings are registered within this bundle
Web Images
- Download the data from the web using an URLSession
- Initialize an UIImage with the data
- Set the ImageView’s image property to the new Image
- Attention:
- Keep threading in mind
- Especially for table views: What happens, if cell is reused before the image was fully loaded?
CoreData Basics
- Apples ORM system
- Integrated with apple platforms
- iOS
- macOS
- …
- Graphical creation and representation of the data model
- Change tracking
- Consistency of relationships among objects
- Lazy loading of objects
- Copy-on-write data sharing to reduce overhead
- Automatic property validation
- Sophisticated query compilation
- Instead of SQL complex queries may be created using NSPredicate
Seite 18 von 26
fi
CoreData Stack
Initialization (Autogenerated)
- > The code for this will get autogenerated
Code generation
- CoreData can automatically generate the entities as
- Classes
- Extension to existing classes
- Or manual code creation be selected
- Class with same name as the entity must be created
- Must inherit from NSManagedObject
- Implement all attributes with the corresponding datatypes
- Mark the attributes @NSManaged
Main Context
- Created automatically for applications with CoreData support
- Using your App (depending on the selected lifecycle type)
- Saving changes to the database
Entities in Code
- Query:
- Let taskList = try context.fetch(Task.fetchRequest())
- Returns all tasks from the database
Seite 19 von 26
- New:
- Let newTask = Task(context: context)
- Creation must be saved to become permanent
- May be deleted before it is saved
- Delete:
- Context.delete(task)
- Deletion must be saved to become permanent
Seite 20 von 26
fi
Concurrency
- A context may only be used on the thread it was created
- Use context.performAndWait{} to send work to the right thread and wait for the result
- Use context.perform {} to send to the right thread but do not wait for the result
- Use persistentContainer.performBackgroundTask { context in } to perform work in a
background thread but do not wait for the result (a new NSMangedObjectTask is created)
- An application may have multiple contexts on multiple threads
- Be careful when deleting items
- May lead to problems, if still referenced on another context!
Background Operations
- Mobile applications should always present up to date data
- No user interaction should be required
- Background loading
- Speci c app feature requires it
- Available APIs
- Background fetch (deprecated since iOS 14.0)
- Background Tasks (iOS 13.0+)
Overview:
Seite 22 von 26
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
Core Location: Overview
- The framework to show the geographic location and orientation of a device
- Available since iOS 2.0
- Uses date from all available components on the device
- Wi-Fi, GPS, Bluetooth, magnetometer, barometer and cellular hardware
Seite 23 von 26
fi
- lets you use features that require apple’s involvement (In-App purchases, iCloud, Push
Noti cations,…)
- This has to be provided with each new version of your app and is also called metadata
- Language
- Promotional screenshots and videos for the app store, app icon
- Description and promo text
- Keywords
- Support information
- Release settings
- Specials information for the reviewer (e.g. credentials for a test account)
If reviewer detects issues with provided metadata, your app will receive a „metadata reject“
-> Screenshots have wrong format
-> privacy URL not working
-> provided test account not working
Seite 24 von 26
fi
fi
fi
ff
fi
fi
fi
fi
fi
7.) Upload your build to App Store Connect
Guidelines
- Review process does not end with app submission
- App might be rejected for not complying to the App Store Review Guidelines
- App gets removed as soon as the rst issue arises!
- Reserve enough time to x all issues, can also appeal a rejection if you think it was rejected
by mistake
- „Metadata rejected“ -> Issues with the app information (metadata) provided in App Store
Connect. The review message will detail the issues. Fix metadata issues and reply to message
+ restart review
- Developer rejected: You can cancel submission by yourself if you identi ed an issue and start
the review after xing it.
- Web clippings:
- Pure container apps (apps that just embed a website into a web view) will be rejected as its
contents and functionality may change completely after the review process.
- Also a substandard UI issue, as the app might now comply to the expected look and feel
Seite 25 von 26
fi
fi
fi
fi
fi
fi
fi
fi
fi
- Repeated submission of similar apps, or not enough lasting value
- Apple wont approve the 4th reskin of the same app under a di erent name
Seite 26 von 26
fi
ff