- How to develop React Native iOS Apps In Windows with Hackintosh (well, sort of)
- Prerequisite
- Step 1: Fetch the Mac installation image
- Step 2: Download VMWare Player
- Step 3: Download Unlocker
- Step 4: Create a New Virtual Machine
- Step 5: Modding the .vmx file
- Руководство React Native — создаем приложение под iOS. Часть 1.1
- Какое приложение мы будем создавать?
- Ремарка
- 1. Создание пустого проекта React Native
- Can i develop react native IOS apps on windows pc #6240
- Comments
- anwar-hussain-e1905 commented Mar 2, 2016
- peterp commented Mar 2, 2016
- chirag04 commented Mar 2, 2016
- anwar-hussain-e1905 commented Mar 2, 2016
- cooolan00p commented Mar 7, 2017
- peterp commented Mar 7, 2017
- cooolan00p commented Mar 7, 2017
- peterp commented Mar 7, 2017
- cooolan00p commented Mar 7, 2017
- kosinw commented Jul 3, 2017
- nzhtrtlc commented Jul 9, 2017 •
- SamiChab commented Sep 8, 2017 •
- optimatex commented Sep 30, 2017
- nzhtrtlc commented Sep 30, 2017 •
- nicoara commented Dec 19, 2017
- stevefan1999-personal commented Dec 24, 2017
- f3ltron commented Feb 2, 2018
How to develop React Native iOS Apps In Windows with Hackintosh (well, sort of)
Steve “Stefan” Fan
May 29, 2017 · 11 min read
Hello Medium! So this is my first story, but I would like to get straight into the game.
I’m kinda frustrated I’m required a physical Mac and iPhone to do iOS React Native development.
I mean, I have MacBook and iPhone, I do have it. And I had to share my repo to my MacBook then run my React Native Builder and React Native Packager, which is kinda verbose and lame. Boo.
Besides, I want to work in a workstation😂, I have a Xeon workstation and it’s sad I had to say goodbye to my keyboard and mouse and hence goodbye to productivity.
Even Xamarin offered a remote iOS Simulator and build agent so we could enjoy developing on our main PC and then push the build on our remote Mac environment. And I doubt the RN team would have the breeze to make that happen.
So I squeezed some of my brain power and finally came out of a solution, which is very, very wacky, crazy and lazy. And here’s the points I’ve thought of:
The Good 1: It works universally, in any x86_64 bit PCs with Virtualization enabled, given you have followed the steps clearly.
The Good 2: You can dispose the environment easily. You can also clone an environment and move it somewhere else.
The Bad 1: It, Just, Works!
The Bad 2: I Don’t recommend you to run any other Mac programs beyond XCode.
The Bad 3: Don’t expect AMD CPUs to run much over this.
The Ugly 1: You need a very beefy, monstrous PC for that, to get merely a fraction of performance on a real Mac.
The Ugly 2: No hardware acceleration, so don’t expect to run and debug OpenGL ES context with it.
If you’re a real man, get a Mac. Otherwise now we’ll discover the journey to Hack-in-to-sh!
(Warning: Practicing Hackintosh is a violation of EULA of both Apple Software and Hardware, and you may face charges and lawsuits, despite the fact no one has been in the past 10 years but a company do , yet we aren’t limited to do anything with our computer, including installing various operating systems, so brace yourself and decide if you’d like to continue stepping on a legal grey zone)
Prerequisite
As I’ve mentioned before, you actually need a very strong and powerful PC! I have a Xeon workstation, but it barely runs well, imagine what kind of nightmare it was to get it hustling, eh?
Also, you need a SSD, unless you have the patience to wait more than 5 minutes to get into your Mac VM with your HDD.
Wait a minute! VM. Hmm…Virtual machine? You’ve guessed it ain’t ya? That’s right, we’ll need VMWare for this.
Step 1: Fetch the Mac installation image
Well, without this we wouldn’t be able to do anything…
If you have a friend that has a Mac, borrow his or her machine…
Download macOS Sierra from App Store…
Go online and find the ritual to rip that installation image into portable DMG/ISO form.
I wouldn’t disclose such method, cause I don’t wanna get no troubles
Transfer the final DMG/ISO file to your main PC. Of course we’ll need it, or how do we…
Step 2: Download VMWare Player
Unless you have VMWare Workstation, which most of us don’t, then we will have to proceed downloading VMWare Player.
Just install it. Should be no problems at all.
Step 3: Download Unlocker
Alright, this is our first hack.
Basically, VMWare locked the essential options preventing OSX and EFI running and cooperating together(hardcode, serial, SMB, etc.) running on any virtual machine instances on all VMWare hypervisor but VMWare Fusion.
So we will have to ‘unlock’ it by patching a few things in order to get Hackintosh working.
After downloading the files by clicking ‘Clone or download’, unzip it, find the files named ‘win-install.cmd’ and ‘win-update-tools.cmd’.
Right click ‘win-install.cmd’ and select ‘Run as Administrator’, same goes ‘win-update-tools.cmd’. This is required to gain access to the Windows Registry and stop VMWare services in order to perform patching.
Step 4: Create a New Virtual Machine
Open up your VMWare Player and just right in the menu select Create a New Virtual Machine.
Then select the installer disc image file you’ve just transferred before.
Then we’ll need to select ‘Apple Mac OS X’ and pick the appropriate version. Here for example, I’m using macOS Sierra, so it was ‘macOS 10.12′, if you’re using El Capitan or Yosemite, get the right version.
Go pass all that options. Remember to configure your VM, I changed the core counts, but most of the time it was OK for the mass.
Step 5: Modding the .vmx file
We’ll have to go around the limitation imposed by VMWare I have mentioned in Step 3. We will have to add an entry to the virtual machine configuration file. Or you will face a core dump during the launching of the VM.
By default, it’s located in ‘
/Documents/Virtual Machine/ / .vmx’ if you haven’t changed the location.
Open it and add the following text in the very end of the file:
Руководство React Native — создаем приложение под iOS. Часть 1.1
Идея создавать мобильные приложения на JS не нова. Мы видели, что фреймворки, такие как Ionic или PhoneGap, справляются с этой задачей и привлекли изрядное количество разработчиков.
Тем не менее ни эти фреймворки, ни идея создавать мобильные приложения на JavaScript никогда не привлекали меня. Я всегда думал, почему бы не изучить Swift/Objective-C или Java и просто делать настоящие приложения? Конечно, это потребует затраты значительных усилий на обучение, но разве непрерывное обучение — это не то, что мы, разработчики, делаем и должны делать хорошо? Быстро изучать новые языки и фреймворки? Тогда в чём смысл? Что касается меня, очевидные преимущества такого подхода никогда не перевешивали сомнения.
Пока я не прочитал статью Chalk + Chisel, в которой обратил внимание на следующее:
Я думал, что React Native — это всего лишь маленький эксперимент. И считал, что настоящее нативное приложение все еще должно писаться на нативных языках. Если бы перемотать время на пару месяцев вперед, я мог бы уверенно сказать, что я никогда больше не буду писать под iOS на Objective-C или Swift.
Что! Вы это… серьёзно?
Чтение такого серьезного утверждения заставило меня дать попытку React Native. Почему нет? Я уже использовал React и он понравился мне. React Native так похож на React, что вы будете чувствовать себя как рыба в воде, если вы уже разрабатываете на React. Если же нет, то к счастью React настолько простой, что может вскружить вам голову.
Какое приложение мы будем создавать?
Я никогда не мог найти нормальное приложение для поиска обоев для моего iPhone в App store.
На десктопе Unsplash — это все что нужно, чтобы удовлетворить все мои потребности. На телефоне же: Настройки → Обои 🙁
Таким образом, в отличие от других руководств, где вы создаёте никому ненужные «Hello World!» счетчики, в этом мы вместе сделаем приложение, которое сможет загружать случайные фото из Unsplash, показывать их в эстетически привлекательном виде и даст возможность сохранять из в Camera Roll (по-видимому аналог «Галереи» в Android, хотя там еще какое-то My Photo Stream есть — прим. переводчика). Это приложение понравилось мне больше, чем я думал. Поэтому, даже если в конце этого руководства, вы не будете впечатлены React Native, у вас останется крутое приложения для поиска и сохранения обоев. Разве это не здорово?
Перед тем, как начнём, перечислю то, с чем вы уже должны быть знакомы на этот момент:
- JavaScript
- Некоторые особенности ES2015, такие как классы, стрелочные функции, деструктуризация и шаблоны-строки($
) (на русском) - Mac OS X командная строка (терминал)
- CSS (неожиданно!)
- React (необязательно)
И еще одно, как я уже говорил, мы будем создавать iOS приложение. Что значит, что вы работаете на Mac. Под Android можно создавать приложения как в Linux, так и в Windows. А под iOS — только в OS X, поэтому подразумевается, что вы работаете в MacOS X.
Ремарка
К концу этого руководства, вы будете достаточно хорошо знакомы с React Native, чтобы писать свои приложения. Мы рассмотрим настройку проекта в Xcode, установку сторонних модулей и компонентов, импортирование библиотек, стилизацию приложения с помощью flexbox, создание настраиваемых обработчиков жестов и другие вещи.
Если вы не использовали React до этого, в этом руководстве мы познакомимся с ним. Это новая крутая библиотека JS с большим потенциалом и, я не думаю, что она перестанет поддерживаться в ближайшее время.
Для вашего удобства руководство разбито на две части. Каждая часть состоит из пяти разделов. В каждом разделе мы двигаемся на один шаг ближе к нашей цели. Я рекомендую вам, если вы начали, заканчивать задание в каждом начатом разделе, поскольку они короткие, чтобы понимать общую концепцию на каждом этапе и не терять концентрации.
Исходный код приложения можно посмотреть на репозитории GitHub.
1. Создание пустого проекта React Native
Убедитесь, что у вас установлен Xcode версии 7.0 или выше. Его можно скачать бесплатно из App Store.
Скорее всего (если вы являетесь веб-разработчиком и читаете это в 2016) у вас уже установлен Node. Если нет, установите его. Другой важный инструмент, который надо установить — это npm (node package manager — менеджер пакетов для Node — прим. переводчика). Node идет с предустановленным npm, вам надо обновить его, поскольку обновления выходят достаточно часто. Следуйте инструкции.
Это все, что нам нужно. Теперь в терминале наберите команду npm install -g react-native-cli . Эта команда установит пакет React Native глобально (ключ (-g). это означает, что из любого проекта, созданного в node вы сможете получить доступ к пакету, установленному глобально. Сами глобальные пакеты устанавливаются в директорию (под windows)… node>node_modules>npm>node_modules — прим. переводчика).
Если всё это кажется вам непонятным или вы не можете выполнить какой-то шаг, вам поможет официальная документация (также моя небольшая заметка по поводу запуска android studio под window7 с процессорами amd — прим. переводчика).
Перейдите в папку, где у вас хранятся проекты через командную строку и наберите в терминале react-native init SplashWalls .
Эта команда загрузит все необходимые модули в новой папке, под названием SplashWalls.
Содержимое папки SplashWalls
Одной из замечательных особенностей React Native является то, что вы пишете приложение под Android и iOS, используя JS, большая часть которого используется в обоих приложениях. В директории есть два файла index.android.js, index.ios.js , названия которых говорят сами за себя. Для разработки под конкретную платформу, вам надо менять соответствующий файл или оба, если вы разрабатываете под обе платформы.
Поскольку мы разрабатываем приложение iOS, мы удалим файл index.android.js и соответствующую папку. Мы будем работать с файлом index.ios.js. Этот файл запускается первым, когда вы запускаете ваше приложение.
Затем перейдите в папку ios и запустите файл SplashWalls.xcodeproj. В Xcode вы увидите следующее всплывающее окно:
Обратите внимание на предупреждение, которое мы видим на скриншоте: «Не найдено совпадающих профилей». Давайте исправим это.
Сначала измените текст в поле Bundle Identifier. Вы должны убедиться в том, что вводимое вами имя соответствует обратной DNS нотификации(зона_домена.название_домена.название_пакета, пример adobe.com > com.adobe.package — прим. переводчика). Это соглашение позволяет различать ваше приложение на App Store. Я буду использовать com.nashvail.me.tutorial.SplashWalls.
Далее выберите ваше имя в списке:
Кликните на Fix Issue.
Пока мы здесь, обратите внимание на пункт Deployment Info. Нам надо кое-что изменить здесь:
Измените настройки следующим образом:
Мы создаём приложение только для портретного вида и прячем статус-бар. Поднимитесь наверх и нажмите кнопку Run в левом верхнем углу Xcode. Это приведет к вызову окна терминала, как показано на скриншоте ниже. Это может занять некоторое время.
По завершении вы должны получить следующий результат в эмуляторе мобильного устройства:
На этом мы закончим с разделом 1 и перейдём к следующему.
Can i develop react native IOS apps on windows pc #6240
Comments
anwar-hussain-e1905 commented Mar 2, 2016
Hi everyone, Can i able to develop react-native IOS apps in my windows pc, if possible then please post what are the requirements and setup require to develop and run react-native ios apps in windows pc
The text was updated successfully, but these errors were encountered:
peterp commented Mar 2, 2016
You’ll need Xcode, which means that you’ll need OS X, which means that you need a Mac or virtualization software.
Here’s a guide: https://blog.udemy.com/xcode-on-windows/. You should more than likely post this on StackOverflow instead.
chirag04 commented Mar 2, 2016
@peterp summarized it nicely. Feel free to post more such questions on stackOverflow or react-native channel on discord if you need any help.
anwar-hussain-e1905 commented Mar 2, 2016
@peterp thanks for your neat information.
cooolan00p commented Mar 7, 2017
Can I create a react native app in windows machine and use the same project for building ios app in a mac?
peterp commented Mar 7, 2017
@cooolan00p Yes, but you’ll be creating one for Android on Windows.
cooolan00p commented Mar 7, 2017
yes, I actually created a project in such a manner that it supports android, ios and web devolopment. When I tried to run it in android, it ran with no issues, but when it came to ios it started showing some errors.
peterp commented Mar 7, 2017
@cooolan00p «learn once, write everywhere» was the slogan, but I think with a bit of knowledge of both the highs and lows in each platform you can do it. 🙂
cooolan00p commented Mar 7, 2017
Finally I got it working. I just changed the strategy.I just started the process all over once and this time on mac, there I checked on the simulator and its working and finally used the same source code in the windows machine and found that its working for android too. finally relieved.
kosinw commented Jul 3, 2017
What about create-react-native-app? As long as you don’t eject, you are able to test your app on iOS and Android by using Expo and the app on the respective device. You can probably find some way to integrate Expo into your existing project, however I don’t have much experience with that.
nzhtrtlc commented Jul 9, 2017 •
You can use expo. With expo you can run ios app on windows. No need mac or xcode.
BUT you need an iphone device. As the result you need at least one apple device.
SamiChab commented Sep 8, 2017 •
Is it possible to generate an .ipa file (iOS application archive file which stores the iOS app) from a windows machine running Expo?
optimatex commented Sep 30, 2017
@nzhtrtlc
Hi. How can I do this? I mean I have iPhone and expo. Which steps should I perform to run ios app on windows?
nzhtrtlc commented Sep 30, 2017 •
@optimatex If i’m not after you follow thesee steps you should be able to run your app in your iphone.
First run your app.
- npm run ios
Then there should be a qrcode. - Scan the qrcode using expo application in your iphone device. If qrcode wont work, try internal ip address. Example: exp://192.168.0.2:19000
After that you’ll be able to debug your app using your real device which is iPhone.
nicoara commented Dec 19, 2017
I have a virtual machine with MacOS on Windows. I want to be able to run the app on my own real iPhone device. How to proceed, given that the exp://192.168,0.2 is a local address that is not visible outside the virtual machine?
Inside Expo XDE, the Device button shows only the simulator, and Share will provide a qr code with the local address.
stevefan1999-personal commented Dec 24, 2017
@nicoara Well you could do this the other way round, shift your Expo/CRNA environment and RNPM in Windows side, find the host-only address in your macOS VM (usually 192.168.6X.X range) and connect to your Windows host.
I’d be covering this in my Medium article but I doubt I have time to do.
f3ltron commented Feb 2, 2018
Expose doesn’t run a real app no ? It just create an app but you can’t access all native feature am i wrong ?