Categories
Uncategorized

Testing automation in iOS

According to Businessofapps, mobile apps become more and more popular. They offer more functions that are in need of testing. This is a crucial process in development. No one wants to use a lousy app that keeps crashing or working bad, right? Also, what if there’s a payment function in an app? Working with a product that can let you down when you send money somewhere isn’t a good idea.

To improve the quality of an app, we need to test it. It’s believed that the developer’s eye eventually starts swimming and they can miss some problems. So, we have testers for that. To increase the speed of testing and implement a system in it, testers automate the process.

Let’s take a look at testing automation using iOS apps as an example. Nowadays, mobile apps have way more functionality than before, so testing takes more time, too. And don’t forget that there are many kinds of iOS devices out there, which increases the time spent on testing even further! To guarantee that an app works correctly on all devices, many tests need to be done, which makes the process longer and more expensive. Testing automation is out there to deal with it because testers won’t need to check some functions manually. It’s enough to write a script and edit it from time to time. Sounds good, doesn’t it? Nothing is perfect, though, so let’s turn to the pros and cons of this method:

Advantages

  • Concurrent testing on multiple devices
  • Faster testing process
  • No human factor. Sometimes, bugs might appear that are difficult to catch. Even if a tester is able to catch those, they can not always understand what the cause was. Automated testing may help with the precision of understanding
  • Testing transparency. When the testers swap, old scripts stay, and the testing process will continue as intended. Regression testing stays the same, too. If you need to change something, or if a new tester wants to check the application logic, the script will work as documentation. This is one of the main advantages

Disadvantages:

  • When iOS updates, you have to wait for the automated testing tools to update, too
  • The tester needs to have special knowledge about automated testing scripts. The company needs to teach employees to do that or hire more expensive ones

The auto testing tools have pros and cons about them. It’s difficult to find a perfect tool, and oftentimes you need to sacrifice convenience in working with a tool or with its possibilities.

When you need automated testing

Do you even need it? The answer is “yes”, if:

  • Your app has too many functions and features, and you are going to support it while adding new things along the way. Why do you need auto testing then? New functionality can conflict with the old one. For example, you’ve introduced a chat and calls broke. To find out the problem, the tester has to test the whole app manually. It takes a lot of time, and the tester is at risk of missing something else! Auto testing helps avoid that problem, as the tester won’t have to test everything after introducing each feature.  Whatever stayed the same will be checked automatically, as long as you launch them and then collect the data. It helps reduce the testing time and the development costs
  • You are going to adapt the app for each new iOS version and take advantage of new system possibilities. Every iOS update can break something within the app. Even if you never planned to update the app in the near future, it might be that you have to. In that case, automated testing will help with that. After that, you’ll understand what it was that broke and be able to solve the problem. Obviously, you wouldn’t add automated testing with this sole purpose, but they will help a great deal if they are already implemented
  • There are testers on your team that possess some knowledge of automated testing. They at least have to know some popular programming language if you go for, say, Appium. Or, they have to know Swift if your choice is XCTest / Earl Gray / KIF. Testers also need to know all the possible testing methods and needed tools. If your employees only know how to manually test apps and have no knowledge of programming languages whatsoever, you will either have to teach them or hire new ones

However, writing automated tests is programming, although you’re not writing new functions for your app but rather a program that goes through your product and checks it. It is expensive. It won’t be worth it to add automated tests if:

  • The app is small. It doesn’t have lots of functions and it is easy to test it manually. With that being said, you are not planning on adding new functions on a constant basis
  • The app is supposed to be developed and distributed within a short period of time, such as those for the World Cup-2018 or the Olympics-2014
  • The app changes frequently. The functionality is unstable. For instance, a startup that looks for its client and keeps changing the main features

Tools for automated testing in iOS

After finding out the main advantages and disadvantages of this approach, let’s take a look at the tools.

XCUITest/XCTest

Apple developed a fully native tool that is out there only for testing iOS apps. Since it is native, external dependencies won’t be there. You develop tests in Swift or Objective-C, which helps developers and testers interact more effectively. However, developing in those languages isn’t that simple. It might be that testers will turn to developers to ask for help far too often, which will make work a bit chaotic. 

There is a test recorder, too. It records real actions with an app and creates a test out of them, but using it is actually quite hard. It isn’t very accurate and it’s best to use it as an assisting tool while developing main tests in Swift or Objective-C. XCUITest/XCTest also works in a separate stream, doesn’t read the state of an app. Therefore, delays in updating the data may lead to an impossibility of seeing requested elements.

EarlGray

The Framework by Google. It requires tests in Objective-C or Swift. The framework synchronizes requests, UI, and streams – that’s the advantage of it. However, EarlGray isn’t very popular because you can only test iOS apps with it. It isn’t very different from XCUITest, yet it is not native, so testers would rather use XCUITest.

KIF

KIF is a framework that has to be added to the project to use it. Objective-C or Swift are the testing languages. Its realism is its main competitive edge. KIF can simulate interaction with a user, therefore it’s very good for UI testing.

You see the iOS-only tools above but when mobile development is in question, oftentimes the developers go for both iOS and Android apps. So no wonder there are cross-platform tools for automated testing.

Detox

JavaScript is a language for tests with Detox. It can access the memory and control ongoing processes. The framework works with emulators and real devices and uses native methods right on the device. It also uses EarlGray and is considered to be really good at testing apps written in React Native, because React Native uses JavaScript, just like Detox. It allows for writing the same tests for Android and iOS.

Appium

Appium is the most popular tool nowadays. It allows testing apps regardless of the platform, type, and system version. Writing tests for each platform is possible using unified API, without transforming an app into a special, network-compatible kind. Appium doesn’t require adding to the app source code. It’s working as a separate tool. Let’s take a look at its advantages:

  • A big number of languages for tests: Java, C#, Python, Ruby. It means that Appium doesn’t only work with Objective-C or Swift, so all testers will be able to create tests
  • An app doesn’t need re-compiling or changing it for automation’s sake. It’s important because the test source code and the app source code aren’t in the same project, and they are developed separately. These two don’t depend on each other, so one can avoid many problems. For example, if somebody wrote the tests incorrectly and they don’t compile, it won’t affect the app in general
  • It is cross-platform. The testers can develop tests for iOS and Android in the same environment, in the same language. They can even re-use the code. It saves time and money
  • Wide functionality. You can launch and stop the app, check the visibility of elements on the screen, and use gestures. Simulator and real devices work with Appium

Appium has some disadvantages, too. It is essentially a superstructure over native iOS and Android drivers. The tests can break more often due to the mistakes in the superstructure code. It’s important to notice here that Appium is very popular, develops quickly, so arising problems will be likely solved in the future.

Conclusion

Automated tests gain popularity in mobile development. They have advantages and disadvantages. Introducing automated tests is worth it when the benefit outweighs the costs. It is not magic, it’s still development, but you’re not developing new functionality but the ways to test the old. If an app has many functions and you keep updating it, but the majority of functions stay the same with each version, take a look at automated testing. After spending money once, you will save more later on.

Testers won’t have to test everything manually with each update. You only changed the teacher’s profile, but all courses, login, payment, booking, admin dashboard have to work the way they did?  The automated tests will have to work for it then. If they didn’t, it means that your small update broke something, now you have to figure out what. If the tests went through – be happy, because the tester will only manually check the teacher’s profile instead of the whole functionality.

We took a look at the tools that enable automated testing. It’s worth saying that we didn’t talk about all the tools out there. There are still paid, unpopular solutions or solutions that are not supported by the developer anymore. Whenever you choose a tool, consider the application’s peculiarities, check if there will be an Android version of the app. Also, consider your tester team! 🙂

We at Fora Soft also use automated testing for some of our projects and find success with it. Do you want to learn more about this topic? Message us using the Contact us form!

Categories
Uncategorized

Native or cross-platform application?

Whenever you create an iOS application, the question you ask first is usually “Do I have to develop a native solution using Swift or go with a cross-platform app?”. You will be able to answer this question, as well as understand the advantages and disadvantages of the both options, after reading this article.

video conference app

Short description of cross-platform solutions

React Native

Facebook created and supports this platform. React Native helps develop cross-platform mobile apps on JavaScript. With that being said, developers are free to use up to 70% of the code between different platforms, such as iOS and Android.

Flutter

Flutter is a young yet promising platform. It has attracted attention from big companies that developed their apps. Flutter’s simplicity is comparable with web applications, and its speed is equal to that of native apps’. The programming language that goes with Flutter is Dart, which compiles into a binary code. That allows operation speed to be comparable to Swift’s and Objective-C’s.

Xamarin

Xamarin is a framework for cross-platform mobile application development, which uses the C# language. Microsoft bought Xamarin in 2016, made the source code of Xamarin SDK open, and included it into IDE Microsoft Visual Studio.

Short description of native solutions

Objective-C

Objective-C used to be the main language of development for iOS until not so long ago. This language is a superset of C, that’s why the compiler Objective-C fully understands C-code. Therefore, an app created with Objective-C can be very fast. Objective-C also has object-oriented programming, which helps make programs that you can easily scale in the future if needed. However, this language is quite old. Stepstone created it in the 1980s. Apple, on the other hand, is a very progressive company, so it wasn’t a huge surprise when they introduced a new programming language in 2014 – Swift.

Swift

Swift is a language that allows writing applications for phones, desktop computers, and servers. The compiler is optimized for productivity, and the language is optimized for development, with no compromises from each side. Swift has years of development behind it, and it’s still moving forward, constantly learning new opportunities. When it was just released, the community split into two parts. The first one believed that there was nothing better than Objective-C. The second one rooted for Swift and tried to use it to create apps. Now, after several years of development, it’s safe to say that when it comes to creating iOS apps, Swift is language #1.

Advantages and disadvantages of cross-platform solutions

The idea of writing an app for iOS and Android simultaneously does draw attention to itself. However, nothing is perfect.

Advantages:

  • Simplicity. Choose between JavaScript, C#, or Dart as the main programming language. More developers can work with those, which will simplify the development process
  • Speed and cost of development. You only need one team of developers to create an app that will look the same on both iOS and Android. When you need to create an app for the both platforms quickly, this becomes a substantial advantage.

Disadvantages:

  • Safety. Almost all cross-platform solutions have an open source code, and any thief who knows how to program can look at it, find the weak spots, and hack your app. It’s also important that a cross-platform app connects with the backend via usual HTTP-calls, and thieves can easily intercept your data and use it for their advantage (read more about it here)
  • The difficulty of work with iOS native functions. Swift developers have integrated useful modules into the language. You can work with audio, video, phone camera, location, Bluetooth with those modules. When developing a cross-platform app, the work with these functions is more difficult. For example, to add an AR-object on a video from a camera or demonstrate a screen during an online call, you need to develop additional modules. It increases the time spent on developing, making it more expensive
  • Speed and interface responsiveness. When an app that shows some data (for example, an online shop or a newsfeed) is developed, the speed of a cross-platform app is equal to a native one, but it will often be lower. If your app supports calls, video chats, AR, it works even slower compared to a native app. Users won’t like it if they miss half of what their interlocutor was speaking about, or if they are unable to catch their favorite Pokemon due to low interface responsiveness.

Advantages and disadvantages of native solutions

According to research conducted by Andrew Madsen’s blog, out of 79 most popular non-game applications in the App Store, about 53% are written in Swift, and the other 47% don’t use Swift. It’s important to mention that somebody from that 47% can be using Objective-C, which is a native language, too.

There is also research by statista.com, which says that ⅔ of all apps are native, for both Android and iOS. Why is that?

Advantages:

  • All peculiarities of a platform are considered. No doubt that developing an app for the both platform at the same time is convenient, but each one of them is individual. Requirements for safety, interface design, and payment system integration differ. For example, system elements that iOS and Android have are absolutely different (the example is on the image below). The user expects to see elements familiar to the platform.
ios and android differences
iOS and Android design differences
  • Speed and interface responsiveness. Native-written apps work faster. It’s a lot more convenient for a user to use an app where the animation is smooth, touching buttons is processed instantly, and they can scroll the screen without freezes, while quickly loading content. It is very important as people are actively using apps nowadays to go shopping, visit doctors, attend business meetings. No one would want their screen to freeze in the moment of payment or during important meetings. These things can make the user look for an alternative
  • No obstacles to updating apps or widen their functionality. Platforms evolve, they add new functions, and apps must support them. An iOS update can completely break an application. Unless cross-platform app developers release a new version, the app may not be working, and there is nothing you can do about it
  • Access to own functions and private API platforms. Swift developers have integrated useful modules into the apps, as we’ve mentioned earlier. Whenever you want to create an app with online conferences, AR, or sharing via Bluetooth (push ads upon entering a Bluetooth tracker area or money transfer in bank apps), the developers won’t have to create these modules themselves, which saves time and money
  • Safety. The source code of operating systems and native ways of development is closed. Gaining access to it is impossible, unlike cross-platform apps with an open source code that anyone can access.

Disadvantages:

  • You need to create two applications
  • You then need to support these two applications

Conclusion

Cross-platform and native ways of development have advantages and disadvantages to them. There is no multi-purpose tool that will be better everywhere. When choosing development tools, take an app type, app’s and platform’s peculiarities, your money, and goals into consideration.

For example, go for a cross-platform solution, if you:

  • Are limited in time and money
  • Need your app to look the same on all platforms, despite their peculiarities
  • Don’t need your app to use platform-specific functions like working with the phone camera, difficult animations, photo and video editing, Bluetooth, online calls
  • Don’t require your app to be extremely safe

Examples: news apps, pizza ordering apps, a beauty salon registering apps, online shops.

On the other hand, go for native tools if your app:

  • Is supported during a long period of time
  • Uses a phone camera, difficult animations, Bluetooth, video and audio calls, streams
  • Requires support for new platform functionality after the platform update
  • Has different design on different platforms
  • Looks the way the platform guidelines recommend
  • Is demanding to safety
  • Requires high speed of work and interface responsiveness, however new and powerful a device is.

Examples: e-learning, medicine, internet TV, video chats, video surveillance, augmented reality.

Categories
Uncategorized

In-App Purchase in iOS apps: how to avoid 30% Apple Pay commission

There are many ways to monetize an application. What affects your choice here are the aims and specifics of your application and the market, for which it was made. One of those methods is organizing purchases within the app. From this text, you will find out how iOS organized the process, what Apple and their competitors provide you with, and why you sometimes will have no choice.

How_To_Avoid_AppStore_Comission

In-App Purchases

This simple and easy to use mechanism was developed by Apple to help organize sales of their apps or of additional features from their apps. Apple takes a 30% fee from every purchase made with In-App Purchases

There are three types of In-App Purchases:

  • Consumable

This purchase can be done multiple times. For example, lives or energy in games.

  • Non-consumable

This purchase can only be done once. For example, a character in a game or a movie in an online theater.

  • Subscriptions (auto-renewable and non-renewable)

A payment that unlocks your app’s functions for a limited period of time. Auto-renewable subscriptions charge users automatically at the end of each paid period. To continue using non-renewable subscriptions, users need to renew them manually. iTunes is an example of that.

A few other payment systems

Stripe is an American company that develops solutions for accepting and processing electronic payments. Stripe allows users to integrate payment processing into their apps without a need to register a merchant account.

Stripe takes 2.9% + 30 cents from each successful transaction.

PayPal is the largest debit digital payment platform. PayPal users are able to pay bills, make purchases, accept, and send money transactions.

PayPal takes from 2.9% to 3.9% commission fee, depending on how expensive the product was. The exact fee amount depends on your sales figures and whether you trade domestically or internationally.

Do I need In-App Purchases?

Apple charges lots of money in comparison to their competitors. Going for Stripe or PayPal might look like a no-brainer, but it’s not so simple. When you develop an iOS application, you face multiple requirements from Apple. One of those requirements prohibits you from making purchases through something other than In-App Purchases.

All digital and virtual goods and services must be paid via In-App Purchases. Therefore, owners of entertainment apps and online movie theaters, digital content sellers, and others must use In-App Purchases.

On the other hand, if you’ve created a mobile app for your online store, tour agency, or air ticket office, the outcome of the deal between you and your buyer is a physical item or a physical document that proves your right to use the service. In that case, you can use an external payment system and get your money fast, avoiding being ripped-off by the App Store.

Categories
Uncategorized

Mobile or web app if a budget is limited to one platform?

A mobile app or a web app? If you want to grow, attract new users, and retain old ones, you will have to do both. All major video service providers have mobile and web applications. Look no further than YouTube, Zoom, Instagram, TikTok, Skype

However, the development costs money, and the money isn’t always enough for all options. What to do, where to start? It’s difficult to answer these questions without any further information. It all comes down to what you want to do and what your plan of development is. In this article, we will explain some things about how to choose a platform and provide you with relevant statistics.

Let’s first take a look at the advantages of both options. Perhaps, it will already be enough for you to make a choice.

Advantages of a web app

  • Availability. A user doesn’t have to download an app from AppStore or Google Play. It’s enough to follow a link or simply google a website
  • Quick updates. The changes to a website go directly to a user
  • A big computer screen allows you to insert more information
  • You can choose a payment system. If you have a mobile app, you will have to pay Google Play or AppStore a 30% commission fee. On a website, you are free to choose any payment system you like, and the commission is ten times lower – 3-4%.
  • You can create a mobile website version. It will work on iOS and Android and cost much less than two native applications. We will compare mobile sites and apps later.

Advantages of a mobile app

  • Convenience. A cellphone is almost always with a user, and they can use an app any time they want.
  • Offline mode. Although a vast majority of apps need internet to work correctly, some developers allow an offline mode for the app. It’s impossible with a website.
  • Push notifications. You can launch a promotion, send an advertisement, or just remind inactive users about the app. SocialMediaToday’s research shows that push notifications are more effective than sending out emails or SMS.

An opportunity to create a mobile website version is a serious advantage when your budget is limited. By doing that, it’s possible to save money on iOS and Android apps. If, however, you think of doing that, you need to consider what you can get and what you can lose.

We get all the website advantages that we had before, plus a user can now use it anywhere where they have a phone and a cell service. It’s also worth noticing that the same development team will create a mobile version of a website. Mobile apps have some advantages, though:

  • Speed. They will launch and work faster. According to research conducted by Kissmetrics, 40% of users leave a website if it takes more than 3 seconds to load. It’s crucial because, according to the very same research, a loading delay in one second can lower conversion by 7%. What it means is that if your website makes $100k a day, you risk losing $2,5 mil a year.
  • Expanded functionality. You are free to use GPS, Bluetooth, camera, and all the platform functions in the app. It can also interact with other apps, integrate with social networks, etc.
  • Mobile apps are used more. Due to research by eMarketer, cellphone users spend 90% of their time on apps and only 10% of their time on websites.

With what do I start?

Although we’ve taken a look at the advantages of mobile apps and web apps, it’s still unclear as to what to go with first if the budget is limited. There’s no all-round solution, and it depends on your product type. Let’s create an algorithm using popular multimedia apps to help us with that.

Target audience

Are you creating an app for business people or just regular users? Your decision might differ based on your answer. As an example, let’s take YouTube and Zoom.

  • YouTube.is a service for regular people. According to official statistics, it’s being used by more than 2 billion people monthly, and 70% of them do that with a mobile app. It’s understandable. Whoever doesn’t watch YouTube nowadays? People go there on their way to work and home, on public transport, in queues, in traffic jams. The mobile app is a go-to thing for YouTube because access from anywhere is essential.
  • Zoom is a video conference service. It’s designed more for meetings and business calls; however, no one prohibits you from calling your mom on Zoom. But it’s the planned direction towards conferences that made Zoom to be used more on desktop computers. Judging by the official statistics, you can see that only about 10% of all registered users went into the meeting using their cellphone.

The conclusion is simple. If you expect your service to be used on a daily basis, and you want it to be accessible anywhere (Instagram, TikTok, WhatsApp), choose a mobile app. If you follow other goals, such as online conferences (Zoom, Google Meet), a web version is your pick. Your partner or employee won’t always be using the service. They will do it during a meeting.

Monetization opportunities 

Do you want to sell subscriptions or goods and services? When you sell digital content inside a mobile app, Google Play or AppStore will take a 30% commission fee. Unlike websites, where the payment will be not that significant, just 3-4%. It’s important because when you start out, you count every cent.

Also, according to Atrium research, people are ready to spend more on a website rather than on mobile apps. That means that if you sell expensive subscriptions, goods, or services, it’s more likely that a user will buy it on a website.

On the other hand, Jmango’s research shows that the conversion rate (a possibility that a user will buy something again later)  is higher on mobile apps.

Android vs. iOS

What to do if you need to create an app, and there is only enough budget for one of those? Let’s turn to the statistics.

According to DeviceAtlas’s research, there are more Android phones out there. But there are regions where that difference is not that substantial, and there are other regions where iOS devices prevail. The knowledge we can take from here is that our decision for a platform will be affected by the market at which the application is aimed. 

For example, in Argentina, Egypt, Brazil, India, and Indonesia iOS devices aren’t popular at all. In the States, Great Britain, Sweden, and Thailand iPhone competes hard with Android phones and sometimes even ends up on top.

BusinessOfApps also reports that those who own Apple devices pay two times more in apps that those with Android. Although there are fewer iOS devices, they are more expensive and are being used by more solvent people. 

DeviceAtlas statistics also show that iOS devices are popular in regions with a higher quality of life. You can see the region statistics for 2018 down below (blue is for iOS, green is for Android).

By the way, the same thing stays with mobile games industry – those with iOS pay more. Gamers from countries with a high quality of life (States, China, Japan), and 48% of the market is from America and China.

If you worry about your target audience age, don’t. Comscore reports that there is no difference in terms of age, so there is no point in diving deeper into this.

Taking everything into account, it’s safe to say that an iOS app is more attractive, and this operating system is better for a single app. iOS application will bring you more money. But it’s worth mentioning that although Apple earns more in general, things might change drastically in some countries. So, if you are looking at Europe, go with iOS. However, if the app is meant for use in a concrete country or city, gather more information, so you don’t have to kick yourself afterward.

There’re also some other peculiarities to consider like overall trends in traffic use habits, 5G impact, etc.

Conclusion

A successful service should provide both mobile and web apps. Different platforms have different advantages and disadvantages and can attract different users. The choice is yours, and we can help you with it.

If you are not sure as to what platform to choose, feel free to contact us, and we will do our best to help you out!

Categories
Uncategorized

WebRTC in iOS: How to Use It in Your iOS [Code Guide]

You’ve probably heard of WebRTC if you wanted to create an online conference app or introduce calls to your application. There’s not much info on that technology, and even those little pieces that exist are developer-oriented. So we aren’t going to dive into the tech part but rather try to understand what WebRTC is.

WebRTC in brief

WebRTC (Web Real Time Communications) is a protocol that allows audio and video transmission in realtime. It works with both UDP and TCP and can switch between them. One of the main advantages of this protocol is that it can connect users via a p2p connection, thus it transmits directly while avoiding servers. However, to use p2p successfully, one must understand p2p’s and WebRTC’s peculiarities.

You can read more in-depth information about WebRTC here

Stun and Turn

Networks are usually designed with private IP addresses. These addresses are used within organizations for systems to be connected locally and they aren’t routed in the Internet. In order to allow a device with a private IP to contact devices and resources outside the local network, a private address must be translated to a publicly accessible address. NAT (Network Address Translation) takes care of the process. You can read more about NAT here. We just need to know that there’s a NAT table in the router and that we need a special record in the NAT which allows packets to our client. To create an entry in the NAT table, the client must send something to a remote client. The problem is that neither of the clients knows their external addresses. To deal with this, STUN and TURN servers were invented. You can connect two clients without TURN and STUN, but it’s only possible if the clients are within the same network.

STUN is directly connected to the Internet server. It receives a packet with an external address of the client that sent it and sends it back. The client learns its external address and the port that’s needed for the router to understand which client has sent the packet. That’s because several clients can simultaneously contact the external network from the internal one. That’s how the entry we need ends up in the NAT table.

TURN is an upgraded STUN server. It can work like STUN, but it also has more functions. For example, you will need TURN when NAT doesn’t allow packets sent by a remote client. It happens because there are different types of NAT, and some of them not only remember an external IP, but also a STUN server port. They don’t allow packets received from servers other than STUN. Not only that, it’s also impossible to establish a p2p connection inside 3G networks. In those cases you also need a TURN server which becomes a relay, making clients think that they’re connected via p2p.

Signal server

We know now why we need STUN and TURN servers, but it’s not the only thing about WebRTC. WebRTC can’t send data about connections, which means that we can’t connect clients using only WebRTC. We need to set up a way to transfer the data about connections (what is the data and why it’s needed, we’ll see below). And for that, we need a signal server. You can use any means for data transfer, you only need the opponents to exchange data among themselves. For instance, Fora Soft usually uses WebSockets.

Video calls one-on-one

Although STUN, TURN, and signal servers have been discussed, it’s still unclear how to create a call. Let’s find out what steps we shall take to organize a video call.

Your iPhone can connect any device via WebRTC. It’s unnecessary for both clients to be related to iPhone, as you can also connect to Android devices or PCs.

We have two clients: a caller and one who’s being called. In order to make a call, a person has to: Receive their local media stream (a stream of video and audio data). Each stream can consist of several media channels. There can be a few media streams: from a camera and a desktop, for example. Media stream synchronizes media tracks, however, media streams can’t be synchronized between each other. Thus, sound and video from the camera will be synchronized with one another but not with the desktop video. Media channels inside the media track are synchronized, too. The code for the local media stream looks like this:

func startLocalStream() {
    let stream = streamsContainer.stream(forIdentifier: PublishStreamModel.publish)
    stream.startCameraCapturer(processDeviceRotations: false, prefferedFrameSize: CGSize(width: 640,height: 480), prefferedFrameRate: 15)
}
  • Create an offer, as in suggesting a call start.
if self.positioningType == .caller {
    self.prepareAndSendOffer()
}
  • Send their own SDP through the signal server. What is SDP? Devices have a multitude of parameters that need to be considered to establish a connection. For example, a set of codecs that work with the device. All these parameters are formed into an SDP object or a session descriptor that is later sent to an opponent via the signal server. It’s important to note that the local SDP is stored as text and can be edited before it’s sent to the signal server. It can be done to forcefully choose a codec. But it’s a rare occasion, and it doesn’t always work.
func stream(_ stream: StreamController?,
            shouldSendSessionDescriptionsessionDescriptionModel: StreamSessionDescriptionModel,
            identifier: String,
            completion: ((Bool)-> ())?) {
    shouldSendSessionDescription?(sessionDescriptionModel, identifier)
}
  • Send their Ice Candidate through a signal server. What’s Ice Candidate? SDP helps establish a logical connection, but the clients can’t find one another physically. Ice Candidate objects possess information about where the client is located in the network. Ice Candidate helps clients find each other and start exchanging media streams. It’s important to notice that that the local SDP is single, while there are many Ice Candidate objects. That happens because the client’s location within the network can be determined by an internal IP-address, TURN server addresses, as well as an external router address, and there can be several of them. Therefore, in order to determine the client’s location within the network, you need a few Ice Candidate objects.
func stream(_ stream: StreamController?,
            shouldSendCandidate candidateModel: StreamCandidateModel,
            identifier: String,
            completion: ((Bool) -> ())?) {
    shouldSendCandidate?(candidateModel, identifier)
}
  • Accept a remote media stream from the opponent and show it. With iOS, OpenGL or Metal can be used as tools for video stream rendering.
func stream(_ stream: StreamController?, shouldShowLocalVideoView videoView: View?, identifier id: String) {
    guard let video = videoView else { return }
    self.localVideo = video
    shouldShowRemoteStream?(video, id)
}

The opponent has to complete the same steps while you’re completing yours, except for the 2nd one. While you’re creating an offer, the opponent is proceeding with the answer, as in answers the call.

if self.positioningType == .callee && self.peerConnection?.localDescription == nil {
    self.prepareAndSendAnswer()
}

Actually, answer and offer are the same thing. The only difference is that while a person expecting a call sets up an answer means, while they generate their local SDP, they rely on the caller’s SDP object. To do that, they refer to the caller’s SDP object. Therefore, the clients know about both device parameters and can choose a more suitable codec.

To summarize: the clients first exchange SDPs (establish a logical connection), then Ice Candidates (establish a physical connection). Therefore, the clients connect successfully, they can see, hear, and talk with each other.

That’s not everything one needs to know when working with WebRTC in iOS. If we leave everything as it is at the moment, the app users will be able to talk. However, only if the application is open, will they be able to learn about an incoming call and answer it. The good thing is, this problem can be easily solved. iOS provides us with a VoIP push. It’s a kind of push notification in iOS, and it was created specifically for work with calls. This is how it’s registered:

// Link to the PushKit framework
import PushKit

// Trigger VoIP registration on launch
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    self.voipRegistration()
    return true
}
    
// Register for VoIP notifications
func voipRegistration() {
    let mainQueue = dispatch_get_main_queue()
    // Create a push registry object
    let voipRegistry: PKPushRegistry = PKPushRegistry(mainQueue)
    // Set the registry's delegate to self
    voipRegistry.delegate = self
    // Set the push type to VoIP
    voipRegistry.desiredPushTypes = [PKPushTypeVoIP]
}

This push notification helps show an incoming call screen which allows the user to accept or decline the call. It’s done via this function:

func reportNewIncomingCall(with UUID: UUID,
                           update: CXCallUpdate,
                           completion: @escaping (Error?) -> Void)

It doesn’t matter what the user is doing at the moment. They can be playing a game or having their phone screen blocked. VoIP push has the highest priority, which means that notifications will always be arriving, and the users will be able to easily call one another. VoIP push notifications have to be integrated along with call integration. It’s very difficult to use calls without VoIP because for a call to happen, the users will have to have their apps open and just sit and wait for the call. That can be classified as strange behavior. The users don’t want to act strange, so they’ll probably choose another application.

Conclusion

We’ve discussed some of the WebRTC peculiarities; found out what’s needed for two clients to connect; learned what steps the clients need to take for a call to happen; what to do besides WebRTC integration to allow iOS users to call one another. We hope that WebRTC isn’t a scary and unknown concept for you anymore, and you understand what you need to apply it to your product. Don’t fear of doing it, as WebRTC is pretty secure!

Categories
Uncategorized

How to apply an effect to a video in iOS

superpower effect

Have you ever thought about how videos are processed? What about applying effects? In this AVFoundation tutorial, I’ll try to explain video processing on iOS in simple terms. This topic is quite complicated yet interesting. You can find a short guide on how to apply the effects down below.

Core Image

Core Image is a framework by Apple for high-performance image processing and analysis. Classes CIImage, CIFilter, and CiContext are the main components of this framework.

With Core Image, you can link different filters together (CiFilter) in order to create custom effects. You can also create the effects that work on the GPU (graphic processor) which will move some load from the CPU (central processor), thus increasing the app speed.

AVFoundation

AVFoundation is a framework for work with media files on iOS, macOS, watchOS, and tvOS. By using AVFoundation, you can easily create, edit, and play QuickTime films and MPEG-4 (MP4) files. You can also play HLS streams (read more about HLS here) and create custom functions to work with video and audio files, such as players, editors, etc.

Adding an effect

Let’s say you need to add an explosion effect to your video. What do you do?

First, you’ll need to prepare three videos: the main one where you’ll apply the effect, the effect video with an alpha channel, and the effect video without an alpha channel.

An alpha channel is an additional channel that can be integrated into an image. It contains information about the image’s transparency and can provide different transparency levels, depending on the alpha type.

We need an alpha channel to not let the video with an effect overlap the main one. This is the example of a picture with the alpha channel and without it:

a picture with the alpha channel and without it

Transparency goes down as the color gets whiter. Therefore, black is fully transparent whereas white is not transparent at all.

After applying a video effect, we’ll only see the explosion itself (the white part of an image on the right), and the rest will be transparent. It will allow us to see the main video where we apply the effect.

Then, we need to read the three videos at the same time and combine the images, using CIFilter. 

First, we get a link to CVImageBuffer via CMSampleBuffer. We need it to control different types of image data. CVImageBuffer is derived from CVPixelBuffer which we’ll need later. We get CIImage from CVImageBuffer. It looks something like this in the code:

CVImageBufferRef imageRecordBuffer = CMSampleBufferGetImageBuffer(recordBuffer);
CIImage *ciBackground = [CIImage imageWithCVPixelBuffer:imageRecordBuffer];
 
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(buffer);
CIImage *ciTop = [CIImage imageWithCVPixelBuffer:imageBuffer];
 
CVImageBufferRef imageAlphaBuffer = CMSampleBufferGetImageBuffer(alphaBuffer);
CIImage *ciMask = [CIImage imageWithCVPixelBuffer:imageAlphaBuffer];

After receiving CIImage for each one of the three videos, we need to compile them using CIFilter. The code will look roughly like this:

CIFilter *filterMask = [CIFilter filterWithName:@"CIBlendWithMask" keysAndValues:@"inputBackgroundImage", ciBackground, @"inputImage", ciTop, @"inputMaskImage", ciMask, nil];
CIImage *outputImage = [filterMask outputImage];

Once again we’ve received CIImage but this time it consists of the three CIImages that we got before. Now, we proceed to render the new CIImage in CVPixelBufferRef using CIIContext. The code will look roughly like this:

CVPixelBufferRef pixelBuffer =[self.contextEffect renderToPixelBufferNew:outputImage];

Now, we have a finalized pixel buffer. We need to add it to the video sample buffer, and we’ll receive a video with the effect after that.

[self.writerAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:CMTimeMake(self.frameUse, 30)]

The effect is successfully added to the video here. With that being said, the work was completed using the GPU, which helped us take the load off the CPU, therefore increase the app speed.

This is cool, right? Actually, there are 9 simple ways to make an iOS app even cooler. How? Check out here!

Conclusion

Adding effects to videos in iOS is quite a complicated task, but it can be done if you know how to use basic frameworks for work with media in iOS. If you want to learn more about it, feel free to get in touch with us via the Contact us form!