📜 ⬆️ ⬇️

Easy way to write iOS apps on the web

Hello. Not so long ago, Gabriel gave us the game 2048 . This is the most amazing case when a clone of the game becomes more popular than the original. Not a small part of the success of Gabriel - open source and, voila, MIT license. Having scored a little more than 20k points, I wanted to share the result with friends, except how to take a screenshot did not work. The appstor looked at the presence of a clone with a game center or something similar - empty. And then I thought, why not?
Looking ahead, it took 4 days to create the application and all the “nishtyakov”. The output is a universal code that works partly on the web and is easily ported to iOS and Android. However, let's go in order.



As you already understood, the discussion will deal with the development of native applications on web technologies. For those who are in the tank, everything works quite simply. A project is created with native SDKs, the purpose of which is to place the WebView full screen and open a specific html in it. Those. it turns out that the entire application is reduced to the browser with a wired address bar. You can argue long, good or bad. In a network of heaps of holivars about this, someone prefers html5, someone has a native code. I am writing this way and that, but here, having the source code for 2048 on the web, it would be foolish to rewrite everything to a native objc. And then, if we are talking about a small application, the main task of which is front-end + working with the server, again it’s stupid to fence objc when you can get by with html5.
Let's just say wunderlist works great on web technologies. Like the official gmail client.

Our team in the main workplace does b2b projects. These are projects where a good ebida is done with minimal attendance. So it is with us, the minimum values ​​are unique per day. Therefore, we can "play" technology. While some are building up for ie8, we told our customers that only firefox or chrome, and they unconditionally set these browsers to the employees. Therefore, we have been using all sorts of html5 for quite a long time and are happy. However, when the idea to make such a project came to mind, I could not even imagine how interesting and new it would be, despite the fact that in general I knew and partially applied almost all the technologies described below.
Let's start with the environment, then we will go through the technologies and discuss the mistakes, draw conclusions.
')
image

1. Environment.

The father of WebView for cell phones, of course, is phoneGap . It is not badly documented (what is there to document it?) And is quite simple. What does he do? Like other frameworks that allow you to create native web-based applications, phonegap pushes native capabilities into JS code and back. Those. you write as written before, adapt the design for a mobile device + have JS calls, allowing you to work with the camera, notifications, contacts, SMS and other things. The list of features and platforms is available on a special page . It was built on the basis of Cordova .
I also advise you to look in the direction of Sencha , the guys went a little further and make it possible not only to get access to native phone / tablet chips via JS, but also give native UI. Those. while making one application, it will look like native in both android and ios. However, sencha is extjs with all that it implies. It's like cilantro, there are people who are crazy about her and people who can not stand her) However, for general information, I advise you to look at it.
I would also like to elaborate on Cordova . Fongap is more surroundings. There is paid support, cloud services for generating applications, etc., etc. Cordova is a platform. Directly native modules and JS binding.

In this case, we will not use any of the above. First, I wanted to try to do everything from scratch. For myself, I decided, further applications only Cordova, the ideal ratio of flexibility and speed. Secondly, I did not manage to quickly deal with the environment of Phongap or Cord. Not to mention sencha. All of them offered to make applications with embedded html, and we now consider the situation when the code lies on an external server.
Why an external server? I wanted to make an application that I could update not when it was moderated in the appstore (usually takes a week), but when I find bugs in it. Let's take it in order.

1.1 TopCoat
There are many frameworks for creating mobile UIs in the network, including those with ala-native UI. Already talked about sencha, just pay attention to PhoneJS , JQ Mobile , Intel AF and many others. Google will tell)
In this case, I chose topcoat. I have already met him on another project and I really liked him. Firstly, these are not bad custom UIs that look great on both android and ios. Secondly, the topcoat is very simple, hence flexible. After Bootstrap it was a little uncomfortable, due to the lack of a grid, naprmer, etc. But you get used to it quickly)
Topcoat has a branch with icons icomatic, I do not recommend. Font awesome best.

1.2 iScroll
UPD: Habrapamer radist2s suggested that iScroll as a whole is not needed if you want to implement close to native scrolling. It turns out enough zayuzat
-webkit-overflow-scrolling: touch; 
Undoubtedly, swipe and scrolling are the calling card of mobile solutions. iScroll gives you very close to native scrolling. Online iScroll4 is not less distributed than the latest iScroll5. Accordingly, the new more advanced and reckless. There are many examples on offsite, in general, everything is clear.

1.3 Zepto
Replacing jQuery, faster selectors and for mobile applications is the most. In large projects, we use jQuery due to the huge number of plugins, all we need is selectors)

1.4 Lodash
Just an auxiliary add-on over JS. We often use backbonejs in projects, lodash is de facto required. Well, in practice, it is not much slower than the native code. Sometimes faster.

1.5 Moment
Work with dates / times in JS. Without comments, without this library, a headache would be many times more.

I did not use Backbone in the project, although he asks very much here. Again, save on matches. Backbone is convenient and indispensable in more or less complex applications, but here it is useless. At least I thought so)
I can not fail to note rad-js , these are custom backbone objects ground for the development of mobile applications. Nice stuff, but pretty sophisticated. It is also very unfortunate that RAD largely uses the old code. For example, it hooks the old iScroll and undercore, instead of lodash. Again, in this project its use seemed redundant.
Deal with the environment. We do not have MVC or similar framework, all the functionality of the application is put into a simple js object. We have a ready css framework and the necessary set of JS libraries for quick development.

image

2. Technology

It's amazing how in the last 2 years technologies and browsers have grown. 2 years ago I chose between web technologies and native code. Under the big project, I chose the native code. And that was the right decision. Now, for good, to rewrite everything on the web and develop further the web. But it’s already a pity, thousands of lines of native obj-c, whether it is not fine. I'm silent about it.

2.1 LocalStorage
Well, everything is clear, storage. 5 meters more than, especially since we need it for text / js-objects. Those who have worked at least once with memokes / radishes will be happy. If 5 meters is not enough, you can bind through the native UserData, for example. There are many solutions online. Someone suggests adding a cache to files, someone via UserData, someone recommends WebSQL, which, by the way, is also convenient. We have enough localStorage.

2.2 AppCache
Perhaps it is only thanks to this technology that we make an application with external code. Once again, our application is not hosted in local html files, but on a remote server. It is logical that if you do not have Internet at the moment, external sites will not open. This is where appCache will save us. About Application cache there were many articles, who have not come across this technology, I advise you to read. The meaning is quite simple. Using a special manifest file, we indicate to the browser all the files that need to be placed in the cache. The beauty is that files placed in the cache will work even if there is no Internet in the device. The logic of the app work in the application is simple.
The client starts the application for the first time, it sucks the content into the webview, the webview caches the application. Next, each time you start the application, the change manifest file is checked. If it has changed, the cache is completely overwritten. If there are no changes, the work continues. Accordingly, if the user does not have the Internet, it just clings to the cache without updates.
Thus, we can do not just native web-based applications, but also place the code directly on our server. For what it is necessary, I wrote above - instant bugfix and fast publishing of new chips.

2.3 CSS3
And, of course, it is foolish to ignore all the possibilities of a webcam. In general, making a mobile application on the web should always remember that we do it with one or two browsers, which are super modern and more often support new technologies than ignore them. Those. it will be good practice to use flexbox, freely use the animation and forget about pngfix)
In this application, almost all the animation is based on css3. First, it is easier and faster than writing kilometers of JS code. Secondly, it works super fast due to hardware acceleration, which can be enabled in the webcam for animation.

Perhaps this is enough) Next, you need to prepare a project in XCode.
As already said, everything is quite simple, we need only a UIWebView on the whole screen and nothing more. I connected to the project JSONKit , because it is faster than the native parser + VK-SDK, Facebook-SDK for integration with social networks. Of course, it was possible to do the integration on the web, but for attractiveness, I wanted to do native support for vk + facebook. Do not forget about the capabilities of ios sdk. Those. Web technologies are cool and powerful, but there are tasks that are best implemented natively. Integration with social networks is one of these tasks, I think.
All that remains for us to do is to establish a connection between our html code and the application. Here, too, everything is quite simple. WebView, what we have placed, you need to make in our controller.
Messages from the application to the web are very simple, from any place we pull:
 [webView stringByEvaluatingJavaScriptFromString:@"alert(123);"] 

Messages from the web to the application work as follows. The done WebView sniffs all transitions, we can make the links we need and intercept them in the shouldStartLoadWithRequest method:
 <button ontouchend="window.location='vk:auth';"></button> 

 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSMutableURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *requestString = [[request URL] absoluteString]; if ([requestString isEqualToString:@"vk:auth"]) { [VKSdk authorize:@[VK_PER_FRIENDS, VK_PER_WALL] revokeAccess:YES forceOAuth:YES inApp:YES display:VK_DISPLAY_IOS]; return NO; } } 

Accordingly, if we intercept the address we need, do not forget to make return NO, otherwise the web version will try to go to the address vk: auth.
In general, that's all, we have a web muzzle that is able to hard cache and work offline and communicate with the native application. What else is needed for happiness? )

Errors and notes for the future


In the next article I will describe how to use Cordova with external code. Undoubtedly, error # 1 was the decision to write its shell on xcode. But again, the task was to study the process in order to understand the whole story. Therefore, it is not entirely a mistake. I do not recommend using their shells, except for reference. In any other projects there is nothing better than Cordova. And all that she does not know how, you can implement in the form of plug-ins for it.
Also, ignoring the backbone was a mistake. The application is already beginning to grow, further refinement would be much simpler and clearer if the mbc backbone framework were used immediately.
Among other things, I was hard fucked with the setting of NSURLRequest. This is the request object for WebView, which, in fact, opens the URL we need. One of the parameters of which is cachePolicy, where you need to transfer the caching policy. For example, you can use the standard policy (approximately corresponds to the browser), or, for example, indicate that the request should never be cached at all, or vice versa, taken only from the cache, regardless of the headers. After reading about the NSURLRequestReloadIgnoringLocalAndRemoteCacheData flag, I decided to use it. The application worked obviously, I left it. And only then it turned out that this flag is not implemented in ios sdk)))

As for the game itself, at the time of sending the binary for moderation, there were no 2048 games in the appstore. At the time of publication there were more than 60 of them. First, I embedded mobile adsense code in the html code. However, before the publication itself, I removed it and made the application a paid one, since All these 60+ games were free with ads inside. It seems like some kind of custom) method of replacing a variable. It should be understood that I have no task to make money on this game, but there is no sense in supporting it for free either. The main difference from competitors is integration not with GameCenter, but with social networks. It is personally more interesting for me to see who I have overtaken among my friends on VK than on the unfilled GameCenter profile. Well, it's easier to follow the "hackers", because base on your server. If such things seem to a group of users more interesting and people will not mind spending 33 rubles per game, it can be developed further. There were ideas to build global rankings, who are gaining more. For example, men or women, adults or teenagers. MGU or MGIMO itp. All this data is collected from social networks.

In any case, this is only a "first attempt at writing." Most of all hemorrhoids I earned by drawing icons in different sizes. A total of 18 icons of different sizes + 13 starting screens.

UPD: Regarding the legality of such applications in the AppStore, I recommend reading the @mifki comments , if everything is as it says, then the application just needs to go through the review and it will not be removed for using the code on the side. However, alamantrah claims that his application was removed for external lua.
Also on StackOverlow, a confirmation was found that earlier the application was not allowed for external scripts, but now the security policy has changed and everything is ok.

Source: https://habr.com/ru/post/216697/


All Articles