Install pods mac os

Install pods mac os

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It has over 86 thousand libraries and is used in over 3 million apps. CocoaPods can help you scale your projects elegantly.

CocoaPods is built with Ruby and is installable with the default Ruby available on macOS. We recommend you use the default ruby.

Using the default Ruby install can require you to use sudo when installing gems. Further installation instructions are in the guides.

Search for pods (above). Then list the dependencies in a text file named Podfile in your Xcode project directory:

Tip: CocoaPods provides a pod init command to create a Podfile with smart defaults. You should use it.

Now you can install the dependencies in your project:

Make sure to always open the Xcode workspace instead of the project file when building your project:

Now you can import your dependencies e.g.:

Sometimes CocoaPods doesn’t yet have a pod for one of your dependencies. Fortunately, creating a pod is pretty easy:

You can find a lot of information on the process in the guides. When you’re done you can get an account and push your pod to the CocoaPods Trunk.

Contribute

We’re developing CocoaPods on GitHub. There’s a guide for getting started on the CocoaPods tool. It’s easy and really gratifying to contribute patches! — for a lot of people it’s their first foray into Open Source. We have some easy tickets to look at.

Источник

CocоaPods — мощное средство в руках Objective-C разработчика

CocoaPods — это мощное и одновременно изящное средство управления зависимостями Cocoa-библиотек, которые разработчики используют в своих iOS и MacOS X проектах. Как обычно для Cocoa-статей мы сфокусируемся именно на iOS разработке.

iOS-разработчики любит использовать наработки других разработчиков (3rd party разработчиков). И как правило, библиотеки поставляются с исходным кодом. И обычно мы добавляем исходный код библиотек в наш проект, однажды взяв его из репозитория разработчиков. У такого подхода есть несколько недостатков:

  • Иногда бывает сложно уследить за версиями библиотек и их связями между собой
  • Нет одного общего места, где можно просмотреть список всех доступных библиотек. Безусловно, github — одно из крупных пристанищ opensource-проектов, но не единственное
  • Необходимо всегда помнить про то, что исходных код таких библиотек нужно обновлять. (отчасти проблему решили бы средства наподобие git submodules)
  • Когда вы скачиваете исходники и добавляете в свой проект часто возникает соблазн изменить код библиотеки локально, что в будущем создать головную боль при обновлении библиотеки.

Средства управлением зависимостями CocoaPods поможет решить многие упомянутые проблемы. CocoaPods разберется с зависимостями между библиотеками, которые вы используете, скачает их, создаст и будет поддерживать структуру проекта в надлежащем виде.

С CocoaPods создать проект, использующий сторонние наработки, намного проще. И так, приступим.

Начинаем

Согласно официальному сайту, CocoaPods — это лучшее средство по управлению зависимостями библиотек в Objective-C проектах.

Вместо скачивания кода из репозитория библиотеки и копирования в папку вашего проекта мы можем предоставить возможность CocoaPods сделать все за нас.

Например, нам необходимо сделать приложение, которые будет общаться с RESTfull API какого-нибудь сервиса, используя JSON.

Наиболее популярная библиотека для работы с HTTP-запросами — это AFNetworking (с тех пор, как ASIHTTPRequest перестала поддерживаться).

Для начала нам необходимо установить CocoaPods. CocoaPods — это Ruby проект, и к нашему счастью интерпретатор Ruby идет в стандартную комплектацию MacOS. Ruby — это единственная зависимость CocoaPods, и сперва нам необходимо обновить список пакетов, в терминале выполнив команду:

Возможно, для корректной работы нам сперва необходимо будет обновить или установить Command Line Tools for XCode. Сделать это можно, зайдя по XCode > Preferences > Downloads > Components.

После того, как список пакетов обновлен, мы можем установить CocoaPods:

sudo gem install cocoapods &&
pod setup

CocoaPods установлен.

Hello World

Создаем новый почти пустой проект File > New > Project… > Single View Applciation, для примера:

Добавляем первую зависимость

Ну вот и он — момент истины. Добавляем нашу первую зависимость в проект.

В терминале переходим в папку проекта и выполняем следующее:
1) Создает Pod-файл

2) Добавляем библиотеку

Как можно увидеть, формат файла завиcимостей довольно простой. Мы добавили строку с AFNetworking и указали, что нас интересует последняя, 0.10.0 версия.
Тут подробно рассказано о формате Pod-файла.

3) Генерируем первоначальное окружение, загружаем необходимые файлы как самого CocoaPods, так и исходники библиотек. И главное — будет всегда поддерживать их в актуальном состоянии:
pod install

После выполнения этих несложных процедур мы получаем новую заготовку проекта. Теперь работать с ним нужно через сгенерированный xcworkspace. То есть забудьте о файле проекта как о самостоятельной сущности, только workspace!

Вот так будет выглядеть структура проекта

Теперь можно смело подключать AFNetworking.h и использовать эту библиотеку будто вы сами только что скачали ее исходники и разместили их в своем проекте.

Собственно, это, пожалуй, основной путь работы с CocoaPods. Основной, минимальный и простой.

Файл с зависимостями можно будет дополнить, разбавив одинокий AFNetworking:

pod ‘SSToolkit’
pod ‘AFNetworking’, ‘>= 0.5.1’
pod ‘CocoaLumberjack’

Суть не меняется, простота работы не пропадает.

Читайте также:  Modern house with large windows

Вот список наиболее популярных библиотек, доступных через CocoaPods:

  • AFNetworking
  • ASIHTTPRequest
  • BlocksKit
  • ConciseKit
  • CorePlot
  • EGOTableViewPullRefresh
  • Facebook-iOS-SDK
  • JSONKit
  • MBProgressHUD
  • Nimbus
  • QuickDialog
  • Reachability
  • SFHFKeychainUtils
  • ShareKit

CocoaPods однозначно можно отнести к must have средствам в арсенале Cocoa-разработчика.

Источник

Устанавливаем CocoaPods и Realm

Jan 19, 2017 · 5 min read

Это руководство по установке CocoaPods и Realm я написал в большей степени для себя, как заметку! Но, если эта статья кому-то пригодится, то я буду только рад. (-:

Итак, начнем!
Сначала краткое пояснение о том …

… что такое CocoaPods?

CocoaPods — это мощное и одновременно изящное средство управления зависимостями Cocoa-библиотек, которые разработчики используют в своих iOS и macOS проектах.

… что такое Realm?

Realm — это кроссплатформенная мобильная баз а данных для iOS (Swift, Objective-C) и Android. Realm построен чтобы быть лучше и быстрее, чем SQLite и Core Data. Она не просто лучше и быстрее, она легка в использовании, и Вы сможете делать много вещей используя всего несколько строк кода.

Установка CocoaPods

Для установки CocoaPods откройте Терминал и введите следующую строку:

Вот и всё! CocoaPods установлен. CocoaPods Guides.

Список часто используемых команд терминала:
help — список команд
help имя_команды — cправка по конкретной команде
cd — перейти в папку выше
cd .. — перескочить в “родную” папку, обычно это /users/имя_пользователя
cd / — перейти в корневую папку диска
cd

— прямой переход в основную папку пользователя /users/имя_пользователя
cd

/Documents — перейти в папку документы принадлежащую тукещему пользователю. Таким образом, можно переходить и в другие папки пользователя
cd Documents/RealmTasks/ — переход в папкуDocuments/RealmTasks/
cd /pictures — попытка перехода в директорию pictures расположенную в КОРНЕВОЙ папке диска
cd pictures — попытка перехода в папку pictures в текущей папке
cd ‘Имя папки’ и cd Имя\ папки — имя папки с “пробелом” должно быть заключено в одинарные кавычки или должен быть обратный слэш перед пробелом
pwd — она показывает, где вы сейчас находитесь (print working directory)

Установка Realm

Для начала, нам необходимо создать в Xcode новый проект “Single View Application” и назовем его “RealmTasks” или как Вам нравиться.

Источник

cocoapods for mac OS

Apr 22, 2018 · 2 min read

while executing command pod Install on your terminal, if your running in to “pod: command not found” follow the below mentioned way to set it up correctly.

Open terminal and type:

Gem will get installed in Ruby inside System library. Or try on 10.11 Mac OSX El Capitan, type:

If there is an error “activesupport requires Ruby version >= 2.xx”, then install latest activesupport first by typing in terminal.

After installation, there will be a lot of messages, read them and if no error found, it means cocoapods installation is done.

Next, you need to setup the cocoapods master repo. Type in terminal:

And wait it will download the master repo. The size can be very big. So, it can take some time. You can track of the download by opening Activity and goto Network tab and search for git-remote-https.

Alternatively you can try adding verbose to the command like so:

pod setup —verbose

Once done it will output “Setup Complete”, and you can create your XCode project and save it.

Then in terminal cd to “your XCode project root directory” (where your .xcodeproj file resides) and type:

Then open your project’s podfile by typing in terminal:

open -a Xcode Podfile

Your Podfile will get open in text mode. Initially there will be some default commands in there. Here is where you add your project’s dependencies. For example, in the podfile, edit it to have all the pods you are looking to have

When you are done editing the podfile, save it and close XCode.

Then install pods into your project by typing in terminal:

Depending how many libraries you added to your podfile for your project, the time to complete this varies. Once completed, there will be a message that says

“Pod installation complete! There are X dependencies from the Podfile and X total pods installed.”

Now close your xcode project and open .xcworkspace xcode project file and start coding.

Источник

How do I install CocoaPods?

I referred to many links and tried, but I had no success. I read CocoaPods documents and many times tried to install, but I always failed because of the starting steps. I found one error whereby I can’t install gems first. What are the steps one by one? Such as steps or a demo of how to install.

This is one link which I tried.

The screenshot refers to this console error I was given:

25 Answers 25

POD Install

Open terminal and type:

The Gem will get installed in Ruby inside the System library. Or try on Mac OS X v10.11 (El Capitan), type:

If there is an error «activesupport requires Ruby version >= 2.xx», then install latest activesupport first by typing in the terminal.

After installation, there will be a lot of messages. Read them and if no error found, it means the CocoaPods installation is done. Next, you need to setup the CocoaPods master repository. Type in the terminal:

And wait it will download the master repository. The size is very big (370.0 MB in December 2016). So it can be a while. You can track of the download by opening Activity and go to the Network tab and search for «git-remote-https». Alternatively, you can try adding «—verbose» to the command like so:

Once done, it will output «Setup Complete», and you can create your Xcode project and save it.

Читайте также:  Secret net ��� linux astra

Then in the terminal, cd to your Xcode project root directory (where your .xcodeproj file resides) and type:

Then open your project’s podfile by typing in terminal:

Your Podfile will get open in text mode. Initially there will be some default commands in there. Here is where you add your project’s dependencies. For example, in the podfile, type

(This line is an example of adding the AFNetworking library to your project.)

Uncomment platform :ios, ‘9.0’
Uncomment user_frameworks! if you’re using Swift

When you are done editing the podfile, save it and close Xcode.

Then install pods into your project by typing in terminal:

Depending how many libraries you added to your podfile for your project, the time to complete this varies. Once completed, there will be a message that says

«Pod installation complete! There are X dependencies from the Podfile and X total pods installed.»

Now close your Xcode project. Then locate and open the .xcworkspace Xcode project file and start coding. (You should no longer open the xcodeproj file.)

First open your terminal

Then update your gem file with command

Then give your project path

Touch the podifle

Open your podfile

It will open a podfile like a text edit. Then set your target. For example if you want to set up Google maps then your podfile should be like

Then install the pod

This works for Mac OS X v10.11.x (El Capitan)

After this, you can set up the pod using pod setup cmd and then move to your project directory and install pod.

On macOS v10.14 (Mojave) with Xcode 10.3, I got scary warnings from the gem route with or without -n /usr/local/bin :

What works for me is still Homebrew. Just:

Simple steps to install a pod file:

Open the terminal

Command on the terminal: sudo gem install cocoapods

Set your project path in the terminal.

Command: pod init

Go to the pod file of your project and add the pod which you want to install

Added in the pod file: pod ‘AFNetworking’, ‘

Command: Pod install

Close the Xcode project

open your project from the terminal

Command: open PodDemos.xcworkspace

These are the complete steps that I usually follow. I am posting these steps as short as possible and assuming that you know about Mac and Xcode projects. First of all, open the terminal and use the following commands, and press enter after each command.

Type in the following command if you don’t already have CocoaPods installed:

Now please move to your Xcode Project directory by using this following command, and replace /Your Xcode Project Directory Path with the actual path to the directory:

Below are instructions for how to use CocoaPods. Please wait for some time after each and every command entered to the terminal to execute successfully.

Searching for pods in terminal:

pod search networking (replace networking with which you want to search)

Creating the pod file:

Opening the pod file:

open -a Xcode Podfile

Adding the pods: (After adding your pods you must save the podfile first and then head back to the terminal again.)

Installing the pods:

Check for updates of pods on existing project:

Update the existing pods:

Uninstall the Cocoapods from system:

sudo gem uninstall cocoapods

There is a complete tutorial for removing pods from your Xcode project on Stack Overflow. You can check on this following link for more info.

  1. Open Terminal
  2. Type in sudo gem install cocoapods if you don’t have CocoaPods
  3. Enter cd /project path , but replace project path with actual project path
  4. touch podfile
  5. Use one of the following commands to open the podfile: open -e podfile to open in TextEdit or open -a pod file to open in Xcode
  6. Set your target and add pod file of GoogleMaps like as:
  7. Use pod install to install dependencies

Year 2020, installing CocoaPods v1.9.1 in macOS v10.15 (Catalina)

First set up your Xcode version in your Mac using the terminal.

Next, install CocoaPods using the terminal.

For more information, visit the official website, https://cocoapods.org/.

Here are all steps with an image. Please follow it properly and I am sure you will not get any error.

First of all, check you have to install command line or not.

You can check this by opening Xcode, navigating the menu to

Xcode → PreferencesDownloadsComponents. Find Command Line Tools and select install/update.

If you haven’t found command line tool then you need to write this command in the terminal:

And click on install.

If you have installed the command-line tool, you need to select your Xcode directory (sometimes these type of problems created due to different versions of Xcode available)

Follow this procedure.

Open terminal and run this command:

Enter the admin password. This could take a while. After a few minutes, it will show a green message if CocoaPods installed successfully in your Mac machine.

If you are getting any error with Xcode 6 like developer path is missing. First run this command in terminal:

sudo xcode-select -switch /Applications/Xcode6.app (or your XCodeName.app)

Now you can set up Pod with your Xcode project.

And now you have to install pod. Follow this procedure.

Change directory to your Xcode project root directory (where your ProjectName.xcodeproj file is placed).

pod setup : (Setting up the CocoaPods master repository)

Читайте также:  Flash tools mac os

If successful, it shows: Setup completed (read-only access). So, you set up everything. Now let’s do something which is more visible…Yes! Let’s install libraries in your Xcode project.

Now you have to set up and update the library related to pod in your project.

Steps to add-remove-update libraries in pod:

Change directory to your Xcode project root directory. If your terminal is already running then there isn’t any need to do this, as you are already at the same path.

open -e podfile (This should open a blank text file)

Add your library names in that text file. You can add new names (library name), remove any name or change the version, e.g.:

NOTE: Use the ( control + ” ) button to add single quote at both end of library name. It should be shown as straight vertical line. Without control button it shall be added as curly single quote which will give error while installation of file.

Save and close this text file. Now libraries are set up and you have to install/update it

Go to your terminal again and run this command: pod install (to install/update these libraries in pod).

You should see output similar to the following:

Note:

If you have followed this whole procedure correctly and step by step, then you can directly fire the pod update command after selecting Xcode and then select your project path. And write your command pod update .

You can also check a command line tool here:

CocoaPods Installation on macOS v10.13 (High Sierra):

Execute the following commands in the terminal:

Pod installation giving an error on Mac OS X v10.11.2 (El Capitan):

ERROR: Error installing cocoapods:
activesupport requires Ruby version >= 2.2.2.

After getting this error, I tried this command and installed again. It worked for me.

Now try the same pod installation command

For me, the easiest way was to install via a Ruby gem:

Please note -v for verbose. It takes a while to install CocoaPods and often you get confused if it’s really happening.

The latest CocoaPods 1.10.0 seem not to be working.

Pod File Install Steps

Normally we use

Solution, fix for CocoaPods error on Mac OS X v10.11 (El Capitan):

In Podfile we need to set the target

In the console — terminal

This worked for me. -n helps you fix the permission error.

Thanks to SwiftBoy’s 10-step solution I successfully used CocoaPods to setup the latest version of AudioKit.

1. Using Xcode create MyAudioApp Swift project saving it to my Developer directory e.g.

2. Using Cocoapods install AudioKit within MyAudioApp project (i.e. install AudioKit sdk)

3. Open Terminal, type command below and press Enter

4. Provide system password and press Enter

5. In Terminal, type command below and press Enter

6. Create project pod file — in Terminal type command below and press Enter

7. Open project pod file — in Terminal type command below and press Enter (opens in TextEdit)

8. Edit code below into open pod file (and save file before quitting TextEdit)

9. To install AudioKit in MyAudioApp workspace type Terminal command below and press Enter

and wait for install to finish

10. In Finder, go to project folder /Users/me/Developer/MyAudioApp and click .xcworkspace file below (opens in Xcode!)

11. In MyAudioApp edit ViewController.swift and insert the following

CocoaPods installation step:

Open your Terminal:

Then go to your project directory with Terminal:

Then enter the below command in Terminal:

(Edit POD file with pod ‘libname’)

For CocoaPods in the terminal, follow this:

If you behind a proxy then pass the proxy as an argument:

  1. Open Terminal
  2. Enter $ sudo gem install cocoapods command in terminal
  3. Create new Xcode project
  4. Navigate to directory containing Xcode project. Use cd “../directory-location/..” or cd [drag-and-drop project folder]
  5. Pod install

If this prompts error Unable to add a source with url.. then install command line tool for Xcode. Again, rerun Pod install command.

This will install all dependencies as well.

Now, open your project in Workspace i.e. Project-Name.xcworkspace rather than Project-Name.xcodeproj

You can install CocoaPods via Homebrew in macOS.

First, open your terminal, and run this code (for installing Homebrew if you have not): Go here for the latest command.

Then install CocoaPods easily via this command:

If you want to install CocoaPods for the first time for your project.

Example: Here we will install the «Alamofire» SDK using CocoaPods step by step.

Step 1. Open Terminal, hit command, and then press the Enter key

Step 2. If it asks, you should provide system password and then press the Enter key

Step 3. With command “cd” and give the path of your project and then press the Enter key

Note: type the «cd» command then space and drag the project folder to the terminal. It will take the project path as shown below (here my project name is: Simple Alamofire)

Step 4. Create a pod file in your project by terminal by command “touch Podfile” and press “Enter”

Step 5. Then, open “Podfile” by terminal command “open Podfile” and press “Enter”

Step 6. Now type following code in opened pod file then save and close file

Step 7. Back in Terminal type command “Pod install” and then press Enter Key.

Step 8. Wait for the install to get complete 100% its around 650+ MB

Step 9. That’s it goto project folder and open below file

Источник

Оцените статью