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 Gabriel's success is open source and, voila, MIT license. Having scored a little more than 20k points, I wanted to share the result with friends, but I couldn’t get a screenshot. The appstore looked at the presence of a clone with a game center or something like that - empty. And then I thought, why not?
    Looking ahead, it took 4 days to create the application and all the “nishtyaks”. The output is a universal code that sometimes works on the web and is easily ported to ios / android. However, let's take it in order.



    As you already understood, we will focus on 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 on the whole screen and open a specific html in it. Those. it turns out that the whole application comes down to a browser with a wired address bar. You can argue for a long time whether this is good or bad. On the net there are lots of holivars about this, some prefer html5, some native code. I write this way and that, but here, having the 2048 source code on the web, it would be foolish to rewrite everything to 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 silly to objc when you can do html5.
    Let's just say wunderlistWorks great on web technologies. Like the official gmail client.

    Our team in the main workplace does b2b projects. These are projects where, with minimal attendance, good ebony is done. So with us, the minimum values ​​of uniki per day. Therefore, we can “play” with technology. While some typeset under IE8, we told our customers that only firefox or chrome, and they unconditionally installed these browsers for employees. Therefore, we have been using all sorts of html5 pieces for a long time and are happy. However, when the idea came to my mind to make such a project, I did 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 go through the technology and discuss the errors, draw conclusions.

    image

    1. The environment.

    The father of WebView for mobiles is undoubtedly phoneGap . It is not poorly documented (what is there to document?) And is quite simple. What is he doing? Like other frameworks that allow you to create native applications based on web technologies, phonegap pushes native features into JS code and vice versa. Those. you write as you wrote before, adapt the design to your mobile device + have JS calls that allow you to work with the camera, notifications, contacts, SMS and more. The list of features and platforms is available on the special page . It is built on the basis of Cordova .
    I also advise you to look towards Sencha, the guys went a little further and make it possible not only to access the native chips of phones / tablets via JS, but also give native UIs. Those. 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 with cilantro, there are people who are crazy about it and people who can’t stand it) However, for general familiarization, I advise you to look at it.
    I would also like to elaborate on Cordova . Fongap, this is more of an environment. 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. Firstly, I wanted to try to do everything from scratch. For myself, I decided that further applications only Cordova, the ideal ratio of flexibility and speed. Secondly, I did not manage to quickly figure out the environment of the fongap or cordova. Not to mention the sencha. All of them offered to make applications with embedded html, and now we will consider the situation when the code is on an external server.
    Why exactly an external server? I wanted to make an application that I could update not when it is moderated in the appstore (usually takes a week), but when I find bugs in it. Let's go in order.

    1.1 TopCoat
    There are many frameworks on the network for creating mobile UIs, including those with native UIs. We have already talked about the Sencha, it is also worth paying attention to PhoneJS , JQ Mobile , Intel AF and many others. Google will tell)
    In this case, I chose topcoat. I 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 bit unusual, in view of the lack of a grid, for example, etc. But you quickly get used to it)
    Topcoat has a branch with icomatic icons, I do not recommend it. Font Awesome is the best.

    1.2 iScroll
    UPD: The user radist2s suggested that iScroll as a whole is not needed if it is necessary to implement close to native scrolling. It turns out just zayuzat
    -webkit-overflow-scrolling: touch;
    
    Undoubtedly, swipes and scrolling are the hallmark of mobile solutions. iScroll gives very close to native scrolling. IScroll4 is no less common on the network than the latest iScroll5. Accordingly, the new more advanced and careless. There are many examples on the offsite, in general, everything is clear.

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

    1.4 Lodash
    Just a helper add-on over JS. We often use backbonejs in projects, lodash is de facto obligatory there. Well, in practice, it is no slower than the native code. Sometimes faster.

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

    I did not use Backbone in the project, although it is very requested here. Again, save on matches. Backbone is convenient and indispensable in more or less complex applications, but here it is useless. At least it seemed to me like that)
    I can’t but mention rad-js , these are custom backbone objects that are designed for mobile application development. Nice thing, but quite sophisticated. It's also a pity that RAD uses a lot of the old code. For example, it clings to the old iScroll and undercore, instead of lodash. Again, in this project, its use seemed superfluous.
    With the environment sorted out. We do not have MVC or a similar framework, all the functionality of the application is placed in a simple js object. We have a ready-made css framework and the necessary set of JS libraries for quick development.

    image

    2. Technology

    It's amazing how technology and browsers have grown over the past 2 years. 2 years ago, I chose between web technologies and native code. For a large project, I chose the native code. And at that moment it was the right decision. Now, for good, rewrite everything on the web and develop further the web. But it’s a pity, thousands of lines of native obj-c, be it not okay. I’m silent about reality.

    2.1 LocalStorage
    Well, everything is clear, the repository. 5 meters more than that, especially since we need it for text / js-objects. Those who have worked at least once with memekes / radish will be happy. If 5 meters is not enough, you can do the strapping through native UserData, for example. There are many solutions online. Someone suggests folding the cache into files, someone through UserData, someone recommends WebSQL, which, by the way, is also convenient. LocalStorage is enough for us.

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

    2.3 CSS3
    Well, of course, it's silly to ignore all the features of a webkit. In general, when making a mobile application on the web, you should always remember that we make it for one or two browsers that are super modern and often support new technologies than ignore them. Those. it’s good practice to use flexbox, freely use animation and forget about pngfix)
    In this application, almost all animation is based on css3. Firstly, it’s easier and faster than writing kilometers of JS code. Secondly, it works super fast thanks to hardware acceleration, which can be included in the webkit for animation.

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

    Messages from the web to the application work as follows. A well-designed WebView sniffs all the transitions, we can make the links we need and intercept them in the shouldStartLoadWithRequest method:

    - (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 intercepted the address we need, do not forget to do return NO, otherwise the web version will still try to go to the address vk: auth.
    That's all and all, we have a web face that can cache hard 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, mistake # 1 was the decision to write your shell in xcode. But again, the task was to study the process in order to understand the ins and outs. Therefore, this is not quite a mistake. I do not recommend using your shells, except for reference. In any other projects, there is nothing better than Cordova. And all that she does not know can be implemented as plugins for her.
    Also, ignoring the backbone was a mistake. The application is already starting to grow, further development would be much simpler and more understandable if the mvc framework like backbone were used immediately.
    Among other things, I went hard with the NSURLRequest setup. This is a request object for WebView, which, in fact, opens the URL we need. One of the parameters of which is cachePolicy, where to send the cache policy. Let's say you can use a standard policy (roughly equivalent to a browser one), 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 was 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 into the html code. However, before the publication itself, I removed it and made the application paid, because All these 60+ games were free with ads inside. It seems like some kind of custom) method of replacing a variable. It is worthwhile to understand that I do not have a 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’s personally more interesting for me to see whom I overtook among my friends on VKontakte than in the blank GameCenter profile. Well, it’s easier to follow “hackers”, because base on your server. If such things seem more interesting to a group of users and people don’t mind spending 33 rubles per game, it can be further developed. There were ideas to build global ratings, who is gaining more. For example, men or women, adults or adolescents. Moscow State University or MGIMO, etc. All this data is collected from social networks.

    In any case, this is just a "test of the pen." Most of the 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 @mifki's comments , if everything is as he says, then the application just needs to go through the review and it will not be deleted for using the code on the side. However, alamantrah claims that his application was removed for external lua.
    Also , confirmation was found on StackOverlow that the application was not allowed for external scripts before, but now the security policy has changed and everything is ok.

    Also popular now: