Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Tech Guides - iOS Programming

10 Articles
article-image-difference-between-native-mobile-development-vs-cross-platform-development
Amarabha Banerjee
27 Jun 2018
4 min read
Save for later

What’s the difference between cross platform and native mobile development?

Amarabha Banerjee
27 Jun 2018
4 min read
Mobile has become an increasingly important part of many modern businesses tech strategy. In everything from eCommerce to financial services, mobile applications aren’t simply a ‘nice to have’, they’re essential. Customers expect them. The most difficult question today isn’t ‘do we need a mobile app’ Instead, it’s ‘which type of mobile app should we build: native vs cross platform?’ There are arguments to be made for cross platform mobile development and native app development. Developers who have worked on either project will probably have an opinion on the right way to go. Like many things in tech, however, the cross platform v native debate is really a question of which one is right for you. From both a business and capability perspective, you need to understand what you want to achieve and when. Let’s take a look at the difference between cross-platform framework or a native development platforms. You should then feel comfortable enough to make the right decision about which mobile platform is right for you. Cross platform development? A cross platform application runs across all mobile operating systems without any extra coding. By all mobile operating systems, I mean iOS and Android (windows phones are probably on their way out). A cross platform framework provides all the tools to help you create cross-platform apps easily. Some of the most popular cross- platform frameworks include: Xamarin Corona SDK appcelerator titanium PhoneGap Hybrid mobile apps One specific form of cross-platform mobile  application is Hybrid. With hybrid mobile apps, the graphical user interface (GUI) is developed using HTML5. These are then wrapped in native webpack containers and deployed on iOS and Android devices. A native app is specifically designed for one particular operating system. This means it will work better in that specific environment than one created for multiple platforms. One of the latest native android development framework is Google Flutter. For iOS, it’s Xcode.. Native mobile development vs Cross platform development If you’re a mobile developer, which is better? Let’s compare cross platform development with mobile development: Cross-platform development is more cost effective. This is simply because you can reuse 80% of your code becase you’re essentially building one application. The cost of native development is roughly double to that of Cross-platform development, although cost of android development is roughly 30% more than iOS development. Cross-platform development takes less time. Although some coding has to be done natively, the time taken to develop one app is, obviously, less than to develop two. Native apps can use all system resources. No other app can have any additional features . They are able to use the maximum computing power provided by the GPU and CPU; this means that load times are often pretty fast.. Cross platform apps have restricted access to system resources. Their access is dependent on framework plugins and permissions. Hybrid apps usually take more time to loadbecause smartphone GPUs are generallyless powerful than other machines. Consequently, unpacking a HTML5 UI takes more time on a mobile device. The same reason forced Facebook to shift their mobile apps from Hybrid to Native which according to facebook, improved their app load time and loading of newsfeed and images in the app. The most common challenge with about cross-platform mobile development is been balancing the requirements of iOS and Android UX design. iOS is quite strict about their UX and UI design formats. That increases the chances of rejection from the app store and causes more recurring cost. A critical aspect of Native mobile apps is that if they are designed properly and properly synchronized with the OS, they get regular software updates. That can be quite a difficult task for cross-platform apps. Finally, the most important consideration that should determine your choice are your (or the customer’s) requirements. If you want to build a brand around your app, like a business or an institution, or your app is going to need a lot of GPU support like a game, then native is the way to go. But if your requirement is simply to create awareness and spread information about an existing brand or business on a limited budget then cross-platform is probably the best route to go down. How to integrate Firebase with NativeScript for cross-platform app development Xamarin Forms 3, the popular cross-platform UI Toolkit, is here! A cross-platform solution with Xamarin.Forms and MVVM architecture  
Read more
  • 0
  • 0
  • 3739

article-image-apple-usb-restricted-mode-everything-you-need-to-know
Amarabha Banerjee
15 Jun 2018
4 min read
Save for later

Apple USB Restricted Mode: Here's Everything You Need to Know

Amarabha Banerjee
15 Jun 2018
4 min read
You must have heard about the incident where the FBI was looking to unlock the iPhone of a mass shooting suspect (one of the attackers in the San Bernardino shooting in 2015). The feds could not unlock the phone, as Apple didn’t budge from their stand of protecting user data. After a few days, police said that they have found a private agency to open the phone. The seed of that feud between the feds and Apple has evolved into a fully grown tree now. This month, Apple announced a new security feature called restricted USB mode. This disables the device’s lightning port after one hour of being locked. Quite expectedly, the law enforcement agencies are not at ease with this particular development. This feature was first introduced in the iOS 11.3 release and then retracted in the next release. But now Apple plans to introduce this feature in the upcoming iOS 12 beta release. The reason as stated by Apple is to protect user data from third party hackers and malwares which have the potential to access iPhone data remotely. You must be wondering, to what extent are these threats genuine. Whether this will mean you locking yourself out of your phone unwittingly with nothing to get you out of the situation. Well, the answer is multilayered. Firstly, if you are not an avid supporter of data privacy and feel you have nothing to hide, then this move might just annoy you for a while. You might wonder about times  when your phone is locked and suddenly forget your unlocking/ passkey. Pretty simple, write it somewhere safe and remember where you have kept it. But in case you are like me, you keep seeing the recent news of user data being hacked, and that worries you. Users are being profiled by different companies for varying end objectives from selling products to shaping up your opinion about politics and other aspects of your life. As such this news might make you a bit comfortable about your next iOS update. Private agencies coming up with solutions to open locked iPhones worried Apple. Companies like Cellebrite and Grayshift are selling devices that can hack any locked Apple device (iPhone and iPad) by using the lightning port. The apparent price of one such device is around 15k USD. What prompted Apple to introduce this security feature into their devices was that government agencies were buying these devices on a regular basis to hack into devices. Hence the threat was real, and the only way to address over 700 million iPhone users’ fears seemed to be introducing the USB restricted mode. The war is however just beginning. Third party companies are already claiming that they have devised a way to overcome this new security feature, which is yet unconfirmed. But Apple is sure to take cognizance of this fact and press their developers more to stay ahead in this cat and mouse game. This has not gone well with the law enforcement agencies as well, they see it as an attempt by Apple to create more hurdles in preventing serious and heinous crimes such as paedophilia. Their side of the argument states that now with the one hour timer since the user locks his or her phone, it becomes much more difficult for them to indict the guilty because they have more room to escape. What do you think this means? Does this give you more faith on your Apple product and will it really compel you to buy that $1200 iPhone with the confidence that your banking data, personal messages, pictures and your other sensitive data are safe at the hands of Apple? Or will it empower the perpetrators of crime to have more confidence that now their activities are not just protected by a passkey, but by an hour of time since they lock it, after which it becomes a black box? No matter what your thoughts are, the war is on, between hackers and Apple. If you belong to either of these communities, these are exciting times. If you are one of the 700 million Apple users, you can feel a bit more secure after the iOS 12 update rolls out. Apple changes app store guidelines on cryptocurrency mining Apple introduces macOS Mojave with UX enhancements like voice memos, redesigned App Store Apple releases iOS 11.4 update with features including AirPlay 2, and HomePod among others
Read more
  • 0
  • 0
  • 2643

article-image-progressive-web-amps-combining-progressive-web-apps-and-amp
Sugandha Lahoti
14 Jun 2018
8 min read
Save for later

Progressive Web AMPs: Combining Progressive Wep Apps and AMP

Sugandha Lahoti
14 Jun 2018
8 min read
Modern day web development is getting harder. Users are looking for relentless, responsive and reliable browsing. They want faster results and richer experiences. In addition to this, Modern apps need to be designed so as to support a large number of ecosystems from mobile web, desktop web, Native ioS, Native Android, Instant articles etc. Every new technology which launches has its own USP. The need for today is combining the features of the various popular mobile tech in the market and reaping their benefits as a combination. Acknowledging the standalones In a study by google it was found that “53% of mobile site visits are abandoned if pages take longer than 3 seconds to load.” This calls for making page loads faster and effortless. A cure for this illness is in the form of AMP or Accelerated Mobile Pages, the brainwork of Google and Twitter. They are blazingly fast web pages purely meant for readability and speed. Essentially they are HTML, most of CSS, but no JavaScript. So heavy duty things such as images are not loaded until they are scrolled into view. In AMPs, links are pre-rendered before you click on them. This is made possible using the AMP caching infrastructure. It automatically caches and calls on the content to be displayed atop the AMP and that is why it feels instant. Because the developers almost never write JavaScript, it leads to a cheap, yet fairly interactive deployment model. However, AMPs are useful for a narrow range of content. They have limited functionality. Users, on the other hand, are also looking for reliability and engagement. This called for the development of what is known as Progressive web apps. Proposed by Google in 2015, PWAs combine the best of mobile and web applications to offer users an enriching experience. Think of Progressive web apps as a website that acts and feels like a complete app. Once the user starts exploring the app within the browser, it progressively becomes smarter, faster and makes user experience richer.  Application Shell Architecture and Service Workers are two core drivers that enable PWA to offer speed and functionality. Key benefits that PWA offers over traditional mobile sites include push notifications, highly responsive UI, all types of hardware access which includes access to camera & microphones, and low data usage to name a few. The concoction: PWA + AMP AMPs are fast and easy to deploy. PWAs are engaging and reliable. AMPs are effortless, more retentive and instant. PWAs supports dynamic content, provides push notifications and web manifests. AMPs work on user acquisition. PWAs enhance user experiences. They seemingly work perfectly well on different levels. But users want to Start quick and Stay quick. They want the content they view to make the first hop blazingly fast, but then provide richer pages by amazing reliability and engagement. This called for combining the features of both into one and this was how Progressive web AMPs was born. PWAMP, as the developers call it, combines the capabilities of native app ecosystem with the reach of the mobile Web. Let us look at how exactly it functions and does the needful. The Best of Both Worlds: Reaping benefits of both AMPs fall back when you have dynamic content. Lack of JavaScript means dynamic functionality such as Payments, or push notifications are unavailable. PWA, on the other hand, can never be as fast as an AMP on the first click. Progressive Web AMPs combines the best features of both by making the first click super fast and then rendering subsequent PWA pages/content. So AMP opens a webpage in the blink of an eye with zero time lag and then the subsequent swift transition to PWA leads to beautiful results with dynamic functionalities. So it starts fast and builds up as users browse further. Now, this merger is made possible using three different ways. AMP as PWA: AMP pages in combination with PWA features This involves enabling PWA features in AMP pages. The user clicks on the link, it boots up fast and you see an AMP page which loads from the AMP cache. On clicking subsequent links, the user moves away from AMP cache to the site’s domain(origin). The website continues using the AMP library, but because it is supported on origin now, service workers become active, making it possible to prompt users (by web manifests) to install a PWA version of their website for a progressive experience. AMP to PWA: AMP pages utilized for a smooth transition to PWA features In PWAs the service workers and app shells kick in only after the second step. Hence AMPs can be a perfect entry point for your apps whereas the user discovers content at fast rates with AMP pages, the service worker of the PWA installs in the background and the user is instantly upgraded to PWA in subsequent clicks which can add push notifications, add reminders, web manifests etc. So basically the next click is also going to be instant. AMP in PWA: AMP as a data source for PWA AMPs are easy and safe to embed. As they are self-contained units, they are easily embeddable in websites. Hence they can be utilized as a data source for PWAs.  AMPs make use of Shadow AMP, which can be introduced in your PWA. This AMP library, loads in the top level page. It can amplify the portions in the content as decided by the developer and connect to a whole load of documents for rendering them out. As the AMP library is compiled and loaded only once for, the entire PWA, it would, in turn, reduce backend implementations and client complexity. How are they used in the real world scenario: Shopping PWAMP offers a high engagement feature to the shoppers. Because AMP sites are automatically kept at the top by Google search engines, AMP attracts the customers to your sites by the faster discovery of the apps. The PWA keeps them thereby allowing a rich, immersive, and app-like shopping experience that keeps the shoppers engaged. Lancôme, the L’Oréal Paris cosmetics brand is soon combining AMP with their existing PWA. Their PWA had led to a 17% year over year increase in the mobile sales. With the addition of AMP, they aim to build lightweight mobile pages that load as fast as possible on smartphones to make the site faster and more engaging. Travel PWAMP features allow users to browse through a list of hotels which instantly loads up at the first click. The customer may then book a hotel of his choice in the subsequent click which upgrades him to the PWA experience. Wego, is a Singapore-based travel service. Its PWAMP has achieved a load time for new users at 1.6 seconds and 1 second for returning customers. This has helped to increase site visits by 26%, reduce bounce rates by 20% and increase conversions by 95%, since its launch. News and Media Progressive Web AMPs are also highly useful in the news apps. As the user engages with content using AMP, PWA downloads in the background creating frictionless, uninterrupted reading. Washington Post has come up with one such app where users can experience the Progressive Web App when reading an AMP article and clicking through to the PWA link when it appears in the menu. In addition, their PWA icon can be added to a user’s home screen through the phone’s browser. All the above examples showcase how the concoction proves to always be fast no matter what. Progressive Web AMPs are progressively enhanced with just one backend-the AMP to rule them all meaning that deploy targets are reduced considerably. So all ecosystems namely web, Android, and iOS are supported with just thin layers of extra code. Thus making them highly beneficial in cases of constrained engineering resources or reduced infrastructure complexity. In addition to this, Progressive Web AMPs are highly useful when a site has a lot of static content on individual pages, such as travel, media, news etc. All these statements assert the fact that PWAMP has the power to provide a full mobile web experience with an artful and strategic combination of the AMP and PWA technologies. To know more about how to build your own Progressive Web AMPs, you can visit the official developer’s website. Top frameworks for building your Progressive Web Apps (PWA) 5 reasons why your next app should be a PWA (progressive web app) Build powerful progressive web apps with Firebase
Read more
  • 0
  • 0
  • 2888
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-ai-on-mobile-how-ai-is-taking-over-the-mobile-devices-marketspace
Sugandha Lahoti
19 Apr 2018
4 min read
Save for later

AI on mobile: How AI is taking over the mobile devices marketspace

Sugandha Lahoti
19 Apr 2018
4 min read
If you look at the current trends in the mobile market space, a lot of mobile phone manufacturers portray artificial intelligence as the chief feature in their mobile phones. The total number of developers who build for mobile is expected to hit 14m mark by 2020, according to Evans Data survey. With this level of competition, developers have resorted to Artificial Intelligence to distinguish their app, or to make their mobile device stand out. AI on Mobile is the next big thing. AI on Mobile can be incorporated in multiple forms. This may include hardware, such as AI chips as seen on Apple’s iPhone X or software-based, such as Google’s TensorFlow for Mobile. Let’s look in detail how smartphone manufacturers and mobile developers are leveraging the power of AI for Mobile for both hardware and software specifications. Embedded chips and In-device AI Mobile Handsets nowadays are equipped with specialized AI chips. These chips are embedded alongside CPUs to handle heavy lifting tasks in smartphones to bring AI on Mobile. These built-in AI engines can not only respond to your commands but also lead the way and make decisions about what it believes is best for you. So, when you take a picture, the smartphone software, leveraging the power of AI hardware correctly identifies the person, object, or location being photographed and also compensates for low-resolution images by predicting the pixels that are missing. When we talk about battery life, AI allocates power to relevant functions eliminating unnecessary use of power. Also, in-device AI reduces data-processing dependency on cloud-based AI, saving both energy, time and associated costs. The past few months have seen a large number of AI-based silicon popping everywhere. The trend first began with Apple’s neural engine, a part of the new A11 processor Apple developed to power the iPhone X.  This neural engine powers the machine learning algorithms that recognize faces and transfer facial expressions onto animated emoji. Competing head first with Apple, Samsung revealed the Exynos 9 Series 9810. The chip features an upgraded processor with neural network capacity for AI-powered apps. Huawei also joined the party with Kirin 970 processor, a dedicated Neural Network Processing Unit (NPU) which was able to process 2,000 images per minute in a benchmark image recognition test. Google announced the open beta of its Tensor Processing Unit 2nd Gen. ARM announced its own AI hardware called Project Trillium, a mobile machine learning processor.  Amazon is also working on a dedicated AI chip for its Echo smart speaker. Google Pixel 2 features a Visual Core co-processor for AI. It offers an AI song recognizer, superior imaging capabilities, and even helps the Google Assistant understand the user commands/questions better. The arrival of AI APIs for Mobile Apart from in-device hardware, smartphones also have witnessed the arrival of Artificially intelligent APIs. These APIs add more power to a smartphone’s capabilities by offering personalization, efficient searching, accurate video and image recognition, and advanced data mining. Let’s look at a few powerful machine learning APIs and libraries targeted solely to Mobile devices. It all began with Facebook announcing Caffe2Go in 2016. This Caffe version was designed for running deep learning models on mobile devices. It condensed the size of image and video processing AI models by 100x, to run neural networks with high efficiency on both iOS and Android. Caffe2Go became the core of Style Transfer, Facebook’s real-time photo stylization tool. Then came Google’s TensorFlow Lite in 2017 announced at the Google I/O conference. Tensorflow Lite is a feather-light upshot for mobile and embedded devices. It is designed to be Lightweight, Speedy, and Cross-platform (the runtime is tailormade to run on various platforms–starting with Android and iOS.) TensorFlow Lite also supports the Android Neural Networks API, which can run computationally intensive operations for machine learning on mobile devices. Following TensorFlow Lite came Apple’s CoreML, a programming framework designed to make it easier to run machine learning models on iOS. Core ML supports Vision for image analysis, Foundation for natural language processing, and GameplayKit for evaluating learned decision trees. CoreML makes it easier for apps to process data locally using machine learning without sending user information to the cloud. It also optimizes models for Apple mobile devices, reducing RAM and power consumption. Artificial Intelligence is finding its way into every aspect of a mobile device, whether it be through hardware with dedicated AI chips or through APIs for running AI-enabled services on hand-held devices. And this is just the beginning. In the near future, AI on Mobile would play a decisive role in driving smartphone innovation possibly being the only distinguishing factor consumers think of while buying a mobile device.
Read more
  • 0
  • 0
  • 3862

article-image-shift-swift-2017
Shawn Major
27 Jan 2017
3 min read
Save for later

Shift to Swift in 2017

Shawn Major
27 Jan 2017
3 min read
It’s a great time to be a Swift developer because this modern programming language has a lot of momentum and community support behind it and a big future ahead of it. Swift became a real contender when it became open source in December 2015, giving developers the power to build their own tools and port it into the environments in which they work. The release of Swift 3 in September 2016 really shook things up by enabling broad scale adoption across multiple platforms – including portability to Linus/x86, Raspberry Pi, and Android. Swift 3 is the “spring cleaning” release that, while not being backwards compatible, has resulted in a massively cleaner language and ensured sound and consistent language fundamentals that will carry across to future releases. If you’re a developer using Swift, the best thing you can do is get on board with Swift 3 as the next release promises to deliver stability from 3.0 onwards. Swift 4 is expected to be released in late 2017 with the goals of providing source stability for Swift 3 code and ABI stability for the Swift standard library. Despite this shake up that occurred with the new release, developers are still enthusiastic about Swift – it was one of the “most loved” programming languages in StackOverflow’s 2015 and 2016 Developer Surveys. Swift was also one of the top 3 trending techs in 2016 as it’s been stealing market share from Objective C. The keen interest that developers have in Swift is reflected by the +35,000 stars it has amassed on Github and the impressive amount of ongoing collaboration between its core team and the wider community. Rumour has it that Google is considering making Swift a “first class” language and that Facebook and Uber are looking to make Swift more central to their operations. Lyft’s migration of its iOS app to Swift in 2015 shows that the lightness, leanness, and maintainability of the code are worth it and services like the web server and toolkit Perfect are proof that the server-side Swift is ready. People are starting to do some cool and surprising things with Swift. Including… Shaping the language itself. Apple has made a repository on Github called swift-evolution that houses proposals for enhancements and changes to the Swift language. Developers are bringing Swift 3 to as many ARM-based systems as possible. For example, you can get Swift 3 for all the Raspberry Pi boards or you can program a robot in Swift on a BeagleBone. IBM has adopted Swift as the core language for their cloud platform. This opens the door to radically simpler app dev. Developers will be able to build the next generation of apps in native Swift from end-to-end, deploy applications with both server and client components, and build microservice APIs on the cloud. The Swift Sandbox lets developers of any level of experience can actively build server-based code. Since launching it’s had over 2 million code runs from over 100 countries. We think there are going to be a lot of exciting opportunities for developers to work with Swift in the near future. The iOS Developer Skill Plan on Mapt is perfect for diving into Swift and we have plenty of Swift 3 books and videos if you have more specific projects in mind.The large community of developers using iOS/OSX and making libraries combined with the growing popularity of Swift as a general-purpose language makes jumping into Swift a worthwhile venture. Interested in what other developers have been up to across the tech landscape? Find out in our free Skill Up: Developer Talk report on the state of software in 2017.
Read more
  • 0
  • 0
  • 1914

article-image-ios-9-speed
Samrat Shaw
20 May 2016
5 min read
Save for later

iOS 9: Up to Speed

Samrat Shaw
20 May 2016
5 min read
iOS 9 is the biggest iOS release to date. The new OS introduced new intricate features and refined existing ones. The biggest focus is on intelligence and proactivity, allowing iOS devices to learn user habits and act on that information. While it isn’t a groundbreaking change like iOS 7, there is a lot of new functionality for developers to learn. Along with iOS 9 and Xcode 7, Apple also announced major changes to the Swift language (Swift 2.0) and announced open source plans. In this post, I will discuss some of my favorite changes and additions in iOS 9. 1 List of new features Let’s examine the new features. 1.1 Search Extensibility Spotlight search in iOS now includes searching within third-party apps. This allows you to deep link from Search in iOS 9. You can allow users to supply relevant information that they can then navigate directly to. When a user clicks on any of the search results, the app will be opened and you can be redirected to the location where the search keyword is present. The new enhancements to the Search API include NSUserActivity APIs, Core Spotlight APIs, and web markup. 1.2 App Thinning App thinning optimizes the install sizes of apps to use the lowest amount of storage space while retaining critical functionality. Thus, users will only download those parts of the binary that are relevant to them. The app's resources are now split, so that if a user installs an app on iPhone 6, they do not download iPad code or other assets that are used to make an app universal. App thinning has three main aspects, namely app slicing, on-demand resources, and bitcode. Faster downloads and more space for other apps and content provide a better user experience. 1.3 3D Touch iPhone 6s and 6s Plus added a whole new dimension to UI interactions. A user can now press the Home screen icon to immediately access functionality provided by an app. Within the app, a user can now press views to see previews of additional content and gain accelerated access to features. 3D Touch works by detecting the amount of pressure that you are applying to your phone's screen in order to perform different actions. In addition to the UITouch APIs, Apple has also provided two new sets of classes, adding 3D Touch functionality to apps: UIPreviewAction and UIApplicationShortcutItem. This unlocks a whole new paradigm of iOS device interaction and will enable a new generation of innovation in upcoming iOS apps. 1.4 App Transport Security (ATS) With the introduction of App Transport Security, Apple is leading by example to improve the security of its operating system. Apple expects developers to adopt App Transport Security in their applications. With App Transport Security enabled, network requests are automatically made over HTTPS instead of HTTP. App Transport Security requires TLS 1.2 or higher. Developers also have an option to disable ATS, either selectively or as a whole, by specifying in the Info.plist of their applications. 1.5 UIStackView The newly introduced UIStackView is similar to Android’s LinearLayout. Developers embed views to the UIStackView (either horizontally or vertically), without the need to specify the auto layout constraints. The constraints are inserted by the UIKit at runtime, thus making it easier for developers. They have the option to specify the spacing between the subviews. It is important to note that UIStackViews don't scroll; they just act as containers that automatically fit their content. 1.6 SFSafariViewController With SFSafariViewController, developers can use nearly all of the benefits of viewing web content inside Safari without forcing users to leave an app. It saves developers a lot of time, since they no longer need to create their own custom browsing experiences. For the users too, it is more convenient, since they will have their passwords pre-filled, not have to leave the app, have their browsing history available, and more. The controller also comes with a built-in reader mode. 1.7 Multitasking for iPad Apple has introduced Slide Over, Split View, and Picture-in-Picture for iPad, thus allowing certain models to use the much larger screen space for more tasks. From the developer point of view, this can be supported by using the iOS AutoLayout and Size Classes. If the code base already uses these, then the app will automatically respond to the new multitasking setup. Starting from Xcode 7, each iOS app template will be preconfigured to support Slide Over and Split View. 1.8 The Contacts Framework Apple has introduced a brand new framework, Contacts. This replaces the function-based AddressBook framework. The Contacts framework provides an object-oriented approach to working with the user's contact information. It also provides an Objective-C API that works well with Swift too. This is a big improvement over the previous method of accessing a user’s contacts with the AddressBook framework. As you can see from this post, there are a lot of exciting new features and capabilities in iOS9 that developers can tap into, thus providing new and exciting apps for the millions of Apple users around the world. About the author Samrat Shaw is a graduate student (software engineering) at the National University Of Singapore and an iOS intern at Massive Infinity.
Read more
  • 0
  • 0
  • 1420
article-image-reactive-programming-swift
Milton Moura
16 Mar 2016
6 min read
Save for later

Reactive Programming in Swift

Milton Moura
16 Mar 2016
6 min read
In this post we will learn how to use some of Swift's functional features to write more concise and expressive code using RxSwift, a reactive programming framework, to manage application states and concurrent tasks. Swift and its functional features Swift can be described as a modern object-oriented language with native support for generic programming. Although it is not a functional language, it has some features that allows us to program using a functional approach, like closures, functions as first-class types, and immutable value types. Nevertheless, Cocoa Touch is an object-oriented framework and bares the constraints that this paradigm enforces. Typical issues that arise in software development projects include managing shared application state and concurrent asynchronous tasks that compete for the data that resides there. Functional programming solves these problems by privileging the immutable state and defining application logic as expressions that do not change during the application's lifecycle. By defining self-contained functions, computations can be easily parallelized and concurrency issues minimized. The Reactive Model The reactive programming model has its roots in FRP (functional reactive programming), which shifts the paradigm from discrete, imperative, command-driven programming to a series of transformations that can be applied to a stream of inputs continously over time. While that might sound like a mouthful, there's nothing quite like a simple example to get a feel for what this means. Expressing a relationship between variables Let's say you have two variables (A and B) whose value changes over the running time of an application, and a third one (C) that derives its own value based on the previous two. 1. var A = 10 2. var B = 20 3. let C = A * 2 + B 4. 5. // Current Values 6. // A = 10, B = 20, C = 40 7. 8. A = 0 9. 10. // Current Values 11. // A = 0, B = 20, C = 40 The definition of C with regards to A and B is evaluated only once, when the assignment operation is executed. The relationship between them is lost immediatly after that. Changing A or B from then on will have no effect on the value of C. At any given moment, to evaluate that expression you must reassign the value of C and calculate it once again, based on the current values of A and B. How would we do this in a reactive programming approach? In the reactive model, we would create two streams that propagate changes in the values of either A or B over time. Each value change is represented as a signal in its corresponding stream. We then combine both streams and assign a transformation that we want to perform on each signal emitted, thus creating a new stream that will emit only transformed values. The usual way to demonstrate this is using Marbles Diagrams, where each line represents the continuity of time and each marble an event that occurs at a determined point in time: Reacting in Cocoa Touch To address this in Cocoa Touch, you could use Key-Value Observing to add observers to the changing variables and handle them when the KVO system notifies you: self.addObserver(self, forKeyPath:"valueA", options: .New, context: nil) self.addObserver(self, forKeyPath:"valueB", options: .New, context: nil) override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { let C = valueA * 2 + valueB } If your variables are tied to the user interface, in UIKit you could define a handler that is invoked when change events are triggered: sliderA.addTarget(self, action: "update", forControlEvents: UIControlEvents.ValueChanged) sliderB.addTarget(self, action: "update", forControlEvents: UIControlEvents.ValueChanged) func update() { let C = sliderA.value * 2 + sliderB.value } But none of these approaches define a persistent and explicit relationship between the variables involved, their lifecycle, and the events that change their value. We can overcome this with a reactive programming model. There are a couple of different implementations currently available for OS X and iOS development such as RxSwift and ReactiveCocoa. We will focus on RxSwift but the basic concepts we address are similar in both frameworks. RxSwift RxSwift extends the Observer pattern to simulate asynchronous streams of data flowing out of your Cocoa Touch objects as if they were typical collections. By extending some of Cocoa Touch's classes with observable streams, you are able to subscribe to their output and use them with composable operations, such as filter(), merge(), map(), reduce(), and others. Returning to our previous example, let's say we have an iOS application with two sliders (sliderA and sliderB) and we wish to continously update a label (labelC) with the same expression we used before (A * 2 + B): 1. combineLatest(sliderA.rx_value, sliderB.rx_value) { 2. $0 * 2 + $1 3. }.map { 4. "Sum of slider values is ($0)" 5. }.bindTo(labelC.rx_text)  We take advantage of the rx_value extension of the UISlider class that transforms the slider's value property into an observable type that emits an item when its value changes. By applying the combineLatest() operation on both slider's observable types, we create a new observable type that emits items whenever any of its source streams emits an item. The resulting emission is a tuple with both slider's values that can be transformed in the operation callback (line 2). Then, we map the transformed value into an informative string (line 4) and bind its value to our label (line 5). By composing three independent operations (combineLatest(), map() and bindTo()) we were able to concisely express a relationship between three objects and continuously update our application's UI, reacting accordingly to changes in the application state. What's next? We are only scratching the surface on what you can do with RxSwift. In the sample source code, you will find an example on how to download online resources using chainable asynchronous tasks. Be sure to check it out if this article sparked your curiosity. Then take some time to read the documentation and learn about the several other API extensions that will help you develop iOS apps in a more functional and expressive way. Discover how patterns in Swift can help you to deal with a large number of similar objects in our article Using the Flyweight Pattern. About the author Milton Moura (@mgcm) is a freelance iOS developer based in Portugal. He has worked professionally in several industries, from aviation to telecommunications and energy and is now fully dedicated to creating amazing applications using Apple technologies. With a passion for design and user interaction, he is also very interested in new approaches to software development. You can find out more at http://defaultbreak.com
Read more
  • 0
  • 0
  • 2976

article-image-swift-2016
Owen Roberts
16 Mar 2016
4 min read
Save for later

Swift in 2016

Owen Roberts
16 Mar 2016
4 min read
It’s only been 2 years since Swift was first released to the public and it’s amazing how quickly it has been adopted by iOS developers all over. Seen as a great jumping point for many people and a perfect alternative to Objective-C with some of the best modern language features built in, like tuples and generics; being Open Source is the icing on the cake for tinker-happy devs looking to make the language their own. Swift is in an interesting position though; despite it being one of the fastest languages being picked up right now, do you know how many apps made by Apple actually use it in iOS 9.2? Only 1. Calculator. It’s not a huge surprise when you think about it – the language is new and constantly evolving, and we can safely assume that Calculator’s use of Swift is to test the water as the features and workings of the language settle down. Maybe in the next 2-3 years Apple will have finally moved to a pure Swift world, but other developers? They’re really jumping into the language. IBM, for example, uses Swift for all its iOS apps. What does this mean for you? It means that, as a developer, you have the ability to help shape a young language that rarely happens on today’s web. So here are a few reasons you should take the plunge and get deeper into Swift in 2016, and if you haven’t started yet, then there’s no better time! Swift 3 is coming What better time to get even deeper into the language when it’s about to add a host of great new features? Swift 3.0 is currently scheduled to launch around the tail end of 2016 and Apple aren’t keeping what they want to include close to their chest. The biggest additions are looking to be stabilizing the ABI, refining the language even more with added resilience to changes, and further increasing portability. All these changes have been on the wishlists of Swift devs for ages and now that we’re finally going to get them there’s sure to be more professional projects made purely in Swift. 3.0 looks to be the edition of Swift that you can use for your customers without worry, so if you haven’t gotten into the language yet, this is the version you should be prepping for! It’s no longer an iOS only language Probably the biggest change to happen to Swift since it became Open Source is that the language is now available on Ubuntu officially, while dedicated fans are also currently creating an Android port of all things. What does this mean for you as a developer? Well, the potential for a greater number of platforms your apps can be deployed on has grown; and one of Swift’s main complaints, that it’s an iOS only language, is rendered moot. It’s getting easier to learn and use In the last 2 years we’ve seen a variety of different tools and package managers for those looking to get more out of Swift. If you’re already using Swift it’s most likely you’re using Xcode to write apps. However, if you’re looking to try something new or just don’t like Xcode then there’s now a host of options for you. Testing frameworks like Quick are starting to appear on the market and alternatives such as AppCode look to build on the feedback the community gives to Xcode and fill in the gaps with what it’s missing. Suggestions as you type and decent project monitoring are becoming more commonplace with these new environments, and there are more environments around if you look, so why not jump on them and see which one suits your style of development? The Swift job market is expanding Last year the Swift job market expanded by an incredible 600%, and that was in its first year alone. With Apple giving Swift its full support and the community having grown so quickly, companies are beginning to take notice. Many companies who produce iOS apps are looking for the benefits that Swift offers over Objective-C and having that language as part of your skillset is something that is beginning to set iOS developers apart from one another… With everything happening with Spring this year it looks to be one of the best times to jump on board or dig deeper into the language. If you’re looking to get started building your Swift skills then be sure to check out our iOS tech page, it has all our most popular iOS books for you to explore along with the list of upcoming titles for you to preorder, Swift included.
Read more
  • 0
  • 0
  • 2044

article-image-swift-missing-pieces-surviving-change
Nicholas Maccharoli
14 Mar 2016
5 min read
Save for later

Swift: Missing Pieces & Surviving Change

Nicholas Maccharoli
14 Mar 2016
5 min read
Change Swift is still a young language when compared to other languages like C, C++, Objective-C, Ruby, and Python. Therefore it is subject to major changes that will often result in code breaking for simple operations like calculating the length of a string. Packaging functionality that is prone to change into operators, functions or computed properties may make dealing with these transitions easier. It will also reduce the number of lines of code that need to be repaired every time Swift undergoes an update. Case study: String Length A great example of something breaking between language updates is the task of getting a string’s character length. In versions of Swift prior to 1.2, the way to calculate the length of a native string was countElements(myString), but then in version 1.2 it became just count(myString). Later at WWDC 2015 Apple announced that many functions that were previously global –such as count - were now implemented as protocol extensions. This resulted in once again having to rewrite parts of existing code as myString.characters.count. So how can one make these code repairs between updates more manageable? With a little help from our friends Computed Properties of course! Say we were to write a line like this every time we wanted to get the length of a string: let length = count(myString) And then all of a sudden this method becomes invalid in the next major release and we have unfortunately calculated the length of our strings this way in, say, over fifty places. Fixing this would require a code change in all fifty places. But could this have been mitigated? Yes, we could have used a computed property on the string called length right from the start: extension String { var length : Int { return self.characters.count } } Had our Swift code originally been written like this, all that would be required is a one line change. This is because the other fifty places would still be receiving a valid Int from the call myString.length. Missing Pieces Swift has some great shorthand and built in operators for things like combining strings - let fileName = fileName + ".txt" - and appending to arrays - waveForms += ["Triangle", "Sawtooth"]. So what about adding one dictionary to another? //Won't work let languageBirthdays = ["C" : 1972, "Objective-C": 1983] + ["python" : 1991, "ruby" : 1995] But it works out of the box in Ruby: compiled = { "C" => 1972, "Objective-C" => 1983 } interpreted = { "Ruby" => 1995, "Python" => 1991 } programming_languages = compiled.merge(interpreted) And Python does not put up much of a fuss either: compiled = {"C":1972, 'Objective-C': 1983} interpreted = {"Ruby":1995, "Python": 1991} programming_languages = compiled.update(interpreted) So how can we make appending one dictionary to another go as smoothly as it does with other container types like arrays in Swift? By overloading the + and += operators to work with dictionaries of course! func + <Key, Value> (var lhs: Dictionary<Key, Value>, rhs: Dictionary<Key, Value>) -> Dictionary<Key, Value> { rhs.forEach { lhs[$0] = $1 } return lhs } func += <Key, Value> (inout lhs: Dictionary<Key, Value>, rhs: Dictionary<Key, Value>) -> Dictionary<Key, Value> { lhs = lhs + rhs return lhs } With a light application of generics and operator overloading we can make the syntax for dictionary addition the same as the syntax for array addition. Operators FTW: Regex Shorthand One thing that you may have encountered during your time with Swift is the lack of support for regular expressions. At the time of writing, Swift is currently at version 2.1.1 and there is no Regular Expression support in the Swift Standard Library. The next best thing to do is to rely on a third party library or Foundation Framework's NSRegularExpression. The issue is that writing code to use NSRegularExpression to find a simple match is a bit long winded every time you wish to check for a match. Putting it into a function is not a bad idea either, but defining an operator may make our code a bit more compact. Taking inspiration from Ruby's =~ regex operator, let’s make a simple version returning a bool representing if there was a match: infix operator =~ { associativity left precedence 140 } func =~ (lhs: String, rhs: String) -> Bool { if let regex = try? NSRegularExpression(pattern: rhs, options: NSRegularExpressionOptions.CaseInsensitive) { let matches = regex.matchesInString(lhs, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, lhs.length)) return matches.count > 0 } else { return false } } (Take note of our trusty length computed property springing to action.) This time around there is no operator as of Swift 2.1 called =~. Therefore, we need to first define the symbol telling the Swift compiler that it is an operator that is infix taking objects on the left and right side, with a precedence of 140, and its associativity is left. Associativity and precedence only matter when there are multiple operators chained together, but I imagine most uses of this operator being something like: guard testStatus =~ "TEST SUCCEEDED" else { reportFailure() } Have fun but be courteous It would be wise to observe The Law of the Instrument and not treat everything as a nail just because you have a hammer in arm’s reach. When making the decision to wrap functionality into an operator or use a computed property in place of the canonical way of coding something explicitly, first ask yourself if this is really improving readability. It could be that you’re just reducing the amount of typing – think about how easily the next person reading your code could adapt. If you want to create even better Swift apps then check out our article to make the most of the Flyweight pattern in Swift - perfect when you need a large number of similar objects! About the author Nick Maccharoli is an iOS / Backend developer and Open Source enthusiast working at a startup in Tokyo and enjoying the current development scene. You can see what he is up to at @din0sr or github.com/nirma
Read more
  • 0
  • 0
  • 1686
article-image-solving-day-7-advent-code-using-swift
Nicky Gerritsen
07 Mar 2016
7 min read
Save for later

Solving Day 7 of Advent of Code using Swift

Nicky Gerritsen
07 Mar 2016
7 min read
Eric Wastl created the website Advent of Code, a website that published a new programming exercise from the first of December until Christmas. I came across this website somewhere in the first few days of December and as I participated in the ACM ICPC in the past, I expected I should be able to solve these problems. I decided it would be a good idea to use Swift to write these solutions. While solving the problems, I came across one problem that I was able to do really well in Swift and I'd like to explain that one in this post. Introduction After reading the problem, I immediately noticed some interesting points: We can model the input as a graph, where each wire is a vertex and each connection in the circuit connects some vertices to another vertex. For example x AND y -> z connect both x and y to vertex z. The example input is ordered in such a way that you can just iterate over the lines from top to bottom and apply the changes. However, the real input does not have this ordering. To get the real input in the correct ordering, one should note that the input is basically a DAG. Or at least it should be, otherwise it cannot be solved. This means we can use topological sorting to sort the vertices of the graph in the order we should walk them. Although in the example input, it seems that AND, OR, NOT, LSHIFT and RSHFT always operated on a wire, this is not the case. They can also operate on a constant value. Implementation Note that I replaced some guard lines with forced unwrapping here. The source code linked at the end contains the original code. First off, we define a Source, which is an element of an operation, i.e. in x AND y both x and y are a Source: enum Source { case Vertex(String) case Constant(UInt16) func valueForGraph(graph: Graph) -> UInt16 { switch self { case let .Vertex(vertex): return graph.vertices[vertex]!.value! case let .Constant(val): return val } } var vertex: String? { switch self { case let .Vertex(v): return v case .Constant(_): return nil } } static func parse(s: String) -> Source { if let i = UInt16(s) { return .Constant(i) } else { return .Vertex(s) } } } A Source is either a Vertex (i.e. a wire) and then it has a corresponding string as identifier, or it is a constant and then it contains some value. We define a function that will return the value for this Source given a Graph (more on this later). For a constant source the whole graph does not matter, but for a wire we should look up the value in the graph. The second function is used to extract the identifier of the vertex of the source, if any. Finally we also have a function that helps us parse a string or integer into a Source. Next up we have an Operation enumeration, which holds all information about one line of input: enum Operation { case Assign(Source) case And(Source, Source) case Or(Source, Source) case Not(Source) case LeftShift(Source, UInt16) case RightShift(Source, UInt16) func applytoGraph(graph: Graph, vertex: String) { let v = graph.vertices[vertex]! switch self { case let .Assign(source1): v.value = source1.valueForGraph(graph) case let .And(source1, source2): v.value = source1.valueForGraph(graph) & source2.valueForGraph(graph) /* etc for other cases */ case let .RightShift(source1, bits): v.value = source1.valueForGraph(graph) >> bits } } static func parseOperation(input: String) -> Operation { if let and = input.rangeOfString(" AND ") { let before = input.substringToIndex(and.startIndex) let after = input.substringFromIndex(and.endIndex) return .And(Source.parse(before), Source.parse(after)) } /* etc for other options */ var sourceVertices: [String] { /* code that switches on self and extracts vertex from each source */ } The operation enum has a static function that allows us to parse a line from the input into an Operation and a function that will allow us to apply it to a graph. Furthermore, it has a computed variable that returns all source vertices for the operation. Now a Vertex is an easy class: class Vertex { var idx: String var outgoing: Set<String> var incoming: Set<String> var operations: [Operation] var value: UInt16? init(idx: String) { self.idx = idx self.outgoing = [] self.incoming = [] self.operations = [] } } It has an ID and keeps track of a set of incoming and outgoing edges (we need both for topological sorting). Furthermore, it has a value (which is initially not set) and a list of operations that has this vertex as target. Because we want to store vertices in a set, we need to let it conform to Equatable and Hashable. Because we have a unique string identifier for each vertex, this is easy: extension Vertex: Equatable {} func ==(lhs: Vertex, rhs: Vertex) -> Bool { return lhs.idx == rhs.idx } extension Vertex: Hashable { var hashValue: Int { return self.idx.hashValue } } The last structure we need is a graph, which basically hold a list of all vertices: class Graph { var vertices: [String: Vertex] init() { self.vertices = [:] } func addVertexIfNotExists(idx: String) { if let _ = self.vertices[idx] { return } self.vertices[idx] = Vertex(idx: idx) } func addOperation(operation: Operation, target: String) { // Add an operation for a given target to this graph self.addVertexIfNotExists(target) self.vertices[target]?.operations.append(operation) let sourceVertices = operation.sourceVertices for v in sourceVertices { self.addVertexIfNotExists(v) self.vertices[target]?.incoming.insert(v) self.vertices[v]?.outgoing.insert(target) } } } We define a helper function that ads a vertex if not already added. We then use this function to define a function that can add operation to the graph, together with all required vertices and edges. Now we need to be able to topologically sort the vertices of the graph, which can be done using Kahn's Algorithm[MA6] . This[MA7]  can be done in Swift almost exactly using the pseudo-code explained there: extension Graph { func topologicalOrder() -> [Vertex] { var L: [Vertex] = [] var S: Set<Vertex> = Set(vertices.values.filter { $0.incoming.count == 0 }) while S.count > 0 { guard let n = S.first else { fatalError("No more nodes in S") } S.remove(n) L.append(n) for midx in n.outgoing { guard let m = self.vertices[midx] else { fatalError("Can not find vertex") } n.outgoing.remove(m.idx) m.incoming.remove(n.idx) if m.incoming.count == 0 { S.insert(m) } } } return L } } Now we are basically done, as we can now write up a function that calculates the value of a given wire in a graph: func getFinalValueInGraph(graph: Graph, vertex: String) -> UInt16? { let topo = graph.topologicalOrder() for vertex in topo { for op in v.operations { op.applytoGraph(graph, vertex: vertex.idx) } } return graph.vertices[vertex]?.value } Conclusions This post (hopefully) gave you some insight intohow I solved one of the bigger Advent of Code problems. As you can see Swift has some really nice features that help in this case, like enums with types and functional methods like filter. If you like these kinds of problems I suggest you go to the Advent of Code website and start solving the problems. There are quite a few that are really easy to get started. The complete code for this blogpost can be found at my GitHub account. About the author Nicky Gerritsen is currently a Software Architect at StreamOne, a small Dutch company specialized in video streaming and storage. In his spare time he loves to code on Swift projects and learn about new things Swift. He can be found on Twitter @nickygerritsen and on GitHub: https://github.com/nickygerritsen/.
Read more
  • 0
  • 0
  • 1809