Getting started

Шестой шаг, Cocoapods интегрировать сторонние рамки в проект

шаг 1: зайдите в xcode, чтобы создать проект

Шаг 2: Откройте терминал и введите путь проекта CD

Примечание. Команда cd означает ввод папки. Путь проекта можно перетащить в терминал, перетаскивая его мышью.

Шаг 3: После ввода пути проекта введите командуvim podfileСоздайте файл подфайла, затем нажмите i, чтобы войти в режим редактирования, появится следующее изображение:

На картинке выше введите

Настроить стороннюю библиотеку для интеграции, нажать клавиатуруescА затем нажмите:Затем введитеwq Нажмите Ввод Наконец введите инструкцию

На этом шаге нет ошибки, указывающей на то, что сторонняя платформа была успешно интегрирована в ваш проект. Откройте рабочее пространство в красном поле, как показано ниже

Что касается iOS, то есть две точки зрения, когда дело доходит до фиксации папки pods.

  • Согласно одной точке зрения, каталог ваших модулей рассматривается как производные данные. Пока у вас есть файлы и , проверенные в вашем проекте, и вы должны … тогда любой теоретически может воссоздать эту среду в любое время, просто запустив . т.е. вам не нужно фиксировать проект pods. package.json и загружает для вас ваши зависимости.

  • Другая школа мысли считает, что, поскольку ваш каталог pods содержит важные файлы, необходимые для запуска вашего проекта … вы должны обязательно проверить его. Таким образом, любой может загрузить весь ваш репозиторий и запустить его. Никаких других шагов не требуется. Это проще для начинающих разработчиков, у которых нет опыта работы с Cocoapods, поскольку компиляция проекта не требует от вас выполнения каких-либо команд. Хотя такой подход может привести к раздутию вашего репозитория, и вы потенциально можете столкнуться с конфликтами слияния подов. Конфликты слияния подов, можно разрешить так же легко. Большинство проектов iOS делают это так.

Эти два пункта выше в основном взяты из этого замечательного видео CocoaPods и Lockfiles

Также стоит отметить, что:

находится в корне (а также ), потому что требуется зафиксировать его в git, поэтому они являются исключениями, в то время как что-либо внутри не требуется фиксировать для того, чтобы что-то работало (даже если некоторые люди делают это по причинам кеширования или еще чего-то), так как все в нем можно регенерировать из и файла блокировки

Вышеупомянутый абзац написан Оливье Халлигоном

Ice Cream Shop, Inc.

Your top client is Ice Cream Shop, Inc. Their ice cream is so popular they can’t keep up with customer orders at the counter. They’ve recruited you to create a sleek iOS app that allows customers to order ice cream right from their iPhones.

You’ve started developing the app and it’s coming along well. Take a look at your progress by opening IceCreamShop.xcodeproj, then building and running. You’ll see a mouth-watering vanilla ice cream cone:

The user should be able to choose an ice cream flavor from this screen, but that’s not possible yet. Your first step is to finish implementing this functionality.

Open Main.storyboard from the Views/Storyboards & Nibs group to see the app’s layout. Here’s a quick overview of the heart of the app, the Choose Your Flavor scene:

  • is the view controller for this scene. It handles user interaction and provides the data for the collection view that displays the different ice cream flavors.
  • is a custom view that displays an ice cream cone based on the backing mode, .
  • is a custom collection view cell that contains a , which gets colors from a model.

While every Ice Cream Shop, Inc. location has signature flavors in common, each carries its own local flavors, too. For this reason, a web service needs to provide the data for the s.

However, this still doesn’t explain why users can’t select their ice cream flavors.

Open PickFlavorViewController.swift, found under the Controllers group, and you’ll see a stubbed method:

private func loadFlavors() {
  // TO-DO: Implement this
}

Aha, there are no flavors! You need to implement the function!

While you could use and write your own networking classes, there’s an easier way: Use Alamofire!

You might be tempted to download this library and drag the source files right into your project. However, that’d be doing it the hard way. CocoaPods provides a much more elegant and nimble solution.

Integrating CocoaPods With Xcode

Now that the Podfile has been set up, CocoaPods can integrate the libraries with your Xcode project.

To do so, open Terminal on your Mac and use to browse to your Xcode project’s directory. Something like this:

Then, simply run the following command in Terminal:

CocoaPods will now read your Podfile, download the appropriate versions of pods listed within, and add them to an Xcode workspace.

Quick Note: CocoaPods will download the main Podspec the first time you use , which is a large file, so it may take a while to download. You may or may not get progress updates, so it may appear as if Terminal is frozen – but it’s not.

It’s important that from this point on, you use the file to develop your app project. You can simply double-click on that file to open the workspace. You’ll see two projects inside: your original project, and a Pods project that CocoaPods added.

And that’s all there is to it! You can use the library in your own iOS app project, and conveniently manage your project’s dependencies from now on.

Quick Tip: If your original Xcode project appears “collapsed” when opening the workspace, make sure to first close the original project in Xcode, and then reopen the workspace.

CocoaPods has a few commands that come in handy:

  • – used initially, and when adding or removing pods
  • – used to list pods that have newer versions available
  • – used to update pods listed in the Podfile, i.e. find newer versions, and install them if available

A common misconception is using when you’re only adding or removing pods in the Podfile. The command is intended to update pods to a newer version, if they’re available. You can also update specific pods with .

It’s worth noting here that CocoaPods keeps track of which pod versions are installed in your project with a file called . It’s a plain text file, saved in your project’s root directory, and – why don’t you have a look at it?

CocoaPods uses to compare the currently installed version of a library against a newly available library version, while taking into account the version constraints you set in your Podfile.

Are you using version control in your project, such as Git? Always push and commit the , otherwise CocoaPods has no way of knowing which pod versions are integrated with the project.

You may choose to include the directory, i.e. the pods themselves, into source control. My personal preference is including them, because it adds some safety and integrity to a project, for example when a library goes AWOL, and because you can build and run the project right after cloning it from the repository.

Как удалить стороннего, который был настроен cocoapods в проекте

В первой части будет рассказано, как удалить стороннюю программу, настроенную с помощью cocoapods в проекте.

1. Откройте Podfile в проекте

2. Удалить командную строку из выбранной сторонней библиотеки

3. Откройте терминал cd в корневом каталоге текущего проекта и повторите команду pod install —verbose —no-repo-update После запуска команды третья сторона Snapkit в проекте была удалена

Часть вторая: удаление кокоапод

В особом случае мы даже не хотим использовать cocoapods. На этот раз мы хотим полностью удалить cocoapods из проекта, не оставляя следов, небольшая проблема,

1. Удалите папки Podfile, Podfile.lock и Pods в папке проекта и файл xcworkspace. 2. Откройте файл xcodeproj, удалите папку Pods и папку Framework в проекте (в настоящее время файлы в этих двух папках отмечены красным, что указывает на то, что в настоящее время эти файлы больше не существуют) ) 3. Удалите файл конфигурации: откройте параметр «Фазы сборки», удалите ресурсы «Check Pods Manifest.lock» и «Copy Pods Resources» и «Embedded Pods Framework» 4. Удалите файлы заголовков и соответствующие коды, указанные в проекте.

Installing Your First Dependency

Your first step is to close Xcode. Yeah, you read that right.

It’s time to create the Podfile, where you’ll define your project’s dependencies.

Open Terminal and navigate to the directory that contains your IceCreamShop project by using the cd command:

cd ~/Path/To/Folder/Containing/IceCreamShop

Next, enter the following command:

pod init

This creates a Podfile for your project.

Finally, type the following command to open the Podfile using Xcode for editing:

open -a Xcode Podfile

Note: Don’t use TextEdit to edit the Podfile because it replaces standard quotes with more graphically-appealing typeset quotes. This can cause CocoaPods to become confused and throw errors. Instead, use Xcode or another programming text editor to edit your Podfile.

The default Podfile looks like this:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'IceCreamShop' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for IceCreamShop

end

Delete the and space before , then delete the other lines starting with .

Your Podfile should now look like this:

platform :ios, '9.0'

target 'IceCreamShop' do
  use_frameworks!

end

This tells CocoaPods your project targets iOS 9.0 and will use frameworks instead of static libraries. While Swift and CocoaPods both support static linking, not all libraries you include do. One of them that you’ll use in this project does not.

If you’ve only programmed in Swift, this may look a bit strange. That’s because the Podfile is actually written in Ruby. You don’t need to know Ruby to use CocoaPods, but you should be aware that even minor text errors will cause CocoaPods to throw errors.

A Word About Libraries

You’ll see the term library often used as a general term that actually means a library or framework. This tutorial is guilty of casually intermixing these words, too.

You may be wondering about the differences between a library, a framework and a CocoaPod. It’s OK if you find the terminology a bit confusing!

A CocoaPod, or pod for short, is a general term for either a library or framework that’s added to your project using CocoaPods.

iOS 8 introduced dynamic frameworks, which allow you to bundle code, images and other assets together. Prior to iOS 8, you created CocoaPods as “fat” static libraries. “Fat” means they contained several code instruction sets, like i386 for the simulator, armv7 for devices, etc. However, Swift doesn’t allow static libraries to contain resources such as images or assets.

Back to Installing Your First Dependency

It’s finally time to add your first dependency using CocoaPods. Add the following to your Podfile, right after :

pod 'Alamofire', '4.9.1'

This tells CocoaPods you want to include Alamofire version 4.9.1 as a dependency for your project.

Save and close the Podfile.

You now need to tell CocoaPods to install the dependencies for your project.

Enter the following command in Terminal, after ensuring you’re still in the directory containing the IceCreamShop project and Podfile:

pod install

You should see output like this:

Analyzing dependencies
Adding spec repo `trunk` with CDN `https://cdn.cocoapods.org/`
Downloading dependencies
Installing Alamofire (4.9.1)
Generating Pods project
Integrating client project

 Please close any current Xcode sessions and use `IceCreamShop.xcworkspace` for this project from now on.
Pod installation complete! There is 1 dependency from the Podfile and 1 total pod installed.

Open the project folder using Finder and you’ll see CocoaPods created a new IceCreamShop.xcworkspace file and a Pods folder to store all the project’s dependencies.

Note: From now on, as the command line warning mentioned, you must always open the project with the .xcworkspace file and not the .xcodeproj. Otherwise, you’ll encounter build errors.

Excellent! You’ve just added your first dependency using CocoaPods!

Установка и использование библиотек

Чтобы сразу продемонстрировать все возможности создадим новый Swift-проект и установим для него Objective-C компонент под названием BEMCheckBox.

Откроем Xcode и создадим самый простой Single View, Swift-проект, я назову его «CocoaPodsExample». Сохраните его в любое место, закройте Xcode, откройте терминал, перейдите в директорию с проектом и напишите:

В корне директории должен появиться новый файл: Podfile. Это обычный текстовый файл с конфигурационным кодом на Ruby, в котором мы должны указать требуемые библиотеки. Обычно все солидные opensource-проекты указывают в Readme, что именно нужно прописать в Podfile для установки, и BEMCheckBox здесь . Откройте его любым текстовым редактором и приведите к следующему виду:

Синтаксис должен быть интуитивно понятен: указываем целевую версию платформы, директива указывает CocoaPods использовать фреймворки вместо статических библиотек (подробности в блоге проекта), а после пишем название библиотеки.

Иногда требуется установить не оригинальную библиотеку, а наиболее акутальный форк от другого автора (например, исправление критичного бага, который ещё не успели смерджить) в таком случае можно использовать следующий синтаксис:

В данном случае мы указываем репозиторий и ветку из которой нужно взять под. Если не указать ветку, то по-умолчанию будет браться master. Аналогично нужно поступать, если вам требуется внести свои изменения в библиотеку: создать форк, закоммитить изменения и сослаться на свой репозиторий в Podfile. Не стоит делать изменения в уже установленных подах, т.к. потом будет очень сложно разобраться (особенно другим разработчикам), почему поведение библиотеки отличается от описанного в оригинальной документации.

Далее запускаем установку командой:

После окончания установки, в директории с проектом должен появиться файл *.xcworkspace, который объединяет созданный нами проект и проект Pods со всеми необходимыми библиотеками и конфигурационными файлами. Теперь для работы с проектом нужно открывать именно воркспейс, а не сам проект (в противном случае ему не будут видны сторонние библиотеки).

Проверить, что библиотека подключилась легко: перейдите на Storyboard, поместите на ViewController UIView из Object Library и в Identity Inspector поставьте ему класс BEMCheckBox (если не получается, то можно попробовать собрать проект ). Запустите проект, и у вас должен появиться работающий чекбокс

Обратите внимание, что мы подключили Objective-C библиотеку к Swift проекту, если вы делали это раньше вручную, то помните, что для этой цели нужно было создавать специальный заголовочный файл Objective-C Bridging Header, но последние версии CocoaPods генерируют его автоматически, поэтому в этом больше нет необходимости

Getting Started

Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial.

Throughout this tutorial, you’ll work with an app called Ice Cream Shop, Inc. You’ll use CocoaPods to add dependencies to the app the easy way, instead of writing your own.

Before you can proceed with this tutorial, you need to install CocoaPods. Fortunately, CocoaPods uses Ruby, which ships with all versions of macOS X since version 10.7.

Open Terminal and enter the following command:

sudo gem install cocoapods

Enter your password when requested. The Terminal output will show various fetching, installing and documentation-related outputs, concluding with “XX gems installed”.

Note: You must use to install CocoaPods, but once it’s installed, you won’t need to use it again in this tutorial.

Finally, enter this command in Terminal to complete the setup:

pod setup --verbose

This process takes a few minutes because it clones the CocoaPods Master Specs repository into ~/.cocoapods/ on your computer.

The option logs progress as the process runs, allowing you to watch the process instead of seeing a seemingly “frozen” screen.

Awesome, you’re now set up to use CocoaPods!

Создать проект Pod

Почему код в проекте Pod проекта может быть импортирован? Так же, как код в проекте AFNetworking может быть импортирован нами, в основном, из-за файла podspec в проекте.

Есть два способа создать проект проекта Pod:

  1. Создавайте файлы podspec вручную, этот метод больше подходит для преобразования существующих проектов в проекты Pod.

  2. Автоматически создавать проекты проекта Pod, этот метод больше подходит для проекта Pod с нуля

Проект, созданный методом 2, будет включать в себя демонстрационный проект. Я предпочитаю использовать этот метод для Pod.

pod lib create

Это команда, предоставляемая Pod для автоматического создания частного проекта pod, по сути, он загружает шаблон проекта Pod в локальный проект, а затем вносит изменения. Во время работы команды для конфигурации появятся несколько элементов конфигурации, которые легко установить по мере необходимости.

image

Каталог проекта выглядит следующим образом:

image

  • Пример: каталог демо-проекта
  • MyUtils: каталог кодов библиотеки
  • ЛИЦЕНЗИЯ: Сертификат с открытым исходным кодом
  • MyUtils.podspec: подспец библиотеки
  • README.md:Readme

Двойной кликMyUtils.xcworkspace Откройте проект, структура проекта выглядит следующим образом:

image

Далее я разместил этот проект на GitHub.

Изменить подспец

  • AFNetworking.podspec
  • Как выбрать лицензию с открытым исходным кодом?

Podspec — это файл конфигурации этого модуля. Когда мы ссылаемся на этот модуль в проекте, он будет настроен в соответствии с элементами конфигурации в этом файле. Кстати, podspec это файл Ruby, мы можем использоватьVisual Studio Code Затем установите плагин Ruby для редактирования, он действительно прост в использовании.

Я сделал простое редактирование podspec этого тестового Pod, конкретные элементы конфигурации здесь не разработаны, вы можете просмотреть:

Подтвердить Pod доступен

Подспец написан. Затем вам нужно проверить, правильно ли он. Есть два метода:

Когда вы видите терминал печати , Это означает, что проверка пройдена, и если она не пройдена, измените ее в соответствии с запросом.

Когда проверка пройдена, отметьте ее и отправьте на удаленный склад

What’s CocoaPods?

Imagine you’re working on an iOS app, and you want to use a third-party library in your project. That third-party library – a so-called dependency – includes code that you want to use in your app, such as for HTTP networking, working with databases, or handling JSON. How are you going to “add” that code to your own iOS app project?

A few approaches might work:

  • You download the library’s code from GitHub, or from the author’s website, and copy it manually into your Xcode project
  • You use a git submodule to add the code to your project, and then sync it via Git
  • You use a package manager, such as CocoaPods, Carthage or Swift Package Manager

Of those 3 options, using a package manager makes the most sense. Here’s why:

  • A package manager helps you manage libraries your code depends on, so it’s easier to add and remove dependencies, and to see exactly what third-party code your project relies on
  • A package manager automatically adds the latest version of a library to your Xcode project, with just a few lines of configuration – it’s super convenient
  • A package manager can work with any release version of a library, i.e. you can specify exactly which version of a library you want, which makes keeping your code conflict-free and up-to-date a lot easier
  • A package manager typically resolves dependencies between libraries, so you won’t run into conflicts when two libraries both rely on the same sub-library
  • A package manager automatically downloads, compiles and links libraries, which speeds up project compile times considerably

In this tutorial, we’ll focus on CocoaPods. It’s the oldest and most mature package manager for iOS (and Mac, tvOS, etc.) and it’s incredibly easy to use.

Here’s how CocoaPods roughly works:

  • You configure the libraries you want added to your iOS app projects in a Podfile, which lists “pods” that need to be integrated with your project, including versions you prefer
  • With a few commands, CocoaPods downloads these libraries (usually from GitHub) and then adds them to a separate Xcode project
  • Both projects are linked together and added to an Xcode workspace, which you’ll use to further develop your iOS project
  • When you compile your app, the Pods project is compiled too, and linked with your iOS project, which means that your project can use the code from the libraries at runtime

A pod also uses a special configuration file, called a “Podspec”, which includes information about the third-party library, such as additional dependencies, versions, license information, and so on. Here’s an example podspec, from Alamofire.

CocoaPods maintains a list of all available libraries and Podspecs. This list will get downloaded the first time you use CocoaPods, and may sometimes need to be re-synced and updated. Because of these Podspecs, CocoaPods knows exactly how to add any third-party library to your iOS project. You can find all libraries on cocoapods.org.

The biggest difference between CocoaPods and Carthage, is that CocoaPods changes your Xcode workspace, whereas Carthage merely builds dependencies and lets you add them to your project yourself. Also, Carthage is decentralized, whereas CocoaPods downloads so-called “specs” from a central location.

Четвертый шаг, проверьте источник ruby ​​и удалите

Сначала проверьте ruby ​​source, gem sources -l:

Затем удалите gem sources —remove https://rubygems.org/ удалить результаты:

Замена внутреннего источника зеркала, причина, по которой добавлен внутренний источник рубинового фарфора, заключается в том, что источник taobao прекратил техническое обслуживание, поэтому источник рубинового фарфора заменен здесь, и постарайтесь убедиться, что есть только один. Введите команду gem sources —add https://gems.ruby-china.org. Результаты замены следующие:

Рубиновый источник уже https://gems.ruby-china.org

【Уведомление об обновлении】

рубиновый источник ужеhttps://gems.ruby-china.com/

причина:

CocoaPods и системы контроля версий

Обычно хорошим тоном в современной разработке является не добавлять сторонние библиотеки под контроль версий. Однако авторы проекта наоборот, хранить директорию Pods/ вместе с проектом. Преимуществом такого подхода является переносимость проекта и отсутствие зависимости от внешних инфраструктур (например Github, где хранится большинство исходных кодов библиотек). С другой стороны, в крупном проекте со множеством библиотек это может существенно увеличить размер репозитория, а в случае командной разработки добавит головной боли при слиянии веток. Поэтому в небольших проектах, где вы являетесь единственным разработчиком, можно смело оставить директорию Pods/ под контролем версий, а в крупных проектах и при командной разработке, лучше добавить ее в .gitignore.

Установка CocoaPods

Менеджер пакетов написан на Ruby и распространяется через RubyGems. В общем случае установка сводится к единственной команде в терминале:

Процесс может занять некоторое (продолжительное) время, не выводя ничего на экран, стоит быть к этому готовым и не прерывать установку до завершения (должна появиться надпись вроде «xx gems installed»).

Далее установим мастер-репозиторий CocoaPods со спецификациями всех доступных проектов. Делается это командой в терминале:

Отмечу, что этот шаг тоже занимает достаточно большой промежуток времени, поэтому я указал ключ , чтобы было видно, что процесс не завис и происходит клонирование репозитория. В зависимости от скорости интернет-соединения, установка мастер-репозитория может занимать от нескольких минут до часа.

Swift Support

CocoaPods version 0.36 was the first version to add support for Swift with the directive.

As long as your app targets iOS8+, you can enable Swift support by adding the directive to your :

Consuming Swift Libraries

With the directive, you can now consume Swift libraries using CocoaPods! After you’ve added to your , you can directly import Swift libraries from your Swift code using the framework name (i.e. ).

Consuming Objective-C Libraries from Swift

With the directive, you can also consume Objective-C libraries from your Swift code without the need of a bridging header anymore. You’ll be able to directly import the framework (i.e. ).

Potential Issue: Unfortunately, all Objective-C Pods haven’t been updated to work with the new dynamic frameworks behavior. You might come across certain Objective-C Pods that no longer build after adding the directive. In these cases you can either not use the directive (you’ll now need to create a ) or manually edit the offending Pod to help it find the headers (as done in the linked issue).

Where to Go From Here?

You can download the completed project using the Download Materials button at the top or bottom of this page.

Congratulations! You now know the basics of using CocoaPods, including creating and modifying dependencies and understanding semantic versioning. You’re now ready to start using them in your own projects!

There’s lots more that you can do with CocoaPods. You can search for existing pods on the official CocoaPods website. Also, refer to the CocoaPods Guides to learn the finer details of this excellent tool. But be warned, once you begin using it, you’ll wonder how you ever managed without it! :]

I hope you enjoyed reading this CocoaPods tutorial as much I did writing it. What are some of your favorite CocoaPods? Which ones do you rely on the most for everyday projects? Feel free to share, or to ask any questions, in the comments below!

How To Install CocoaPods

Installing CocoaPods is fairly easy. CocoaPods is built with Ruby, a popular and robust programming language. It’s distributed as a so-called “gem”, which is – how meta! – Ruby’s way of package management. Ruby is installed by default on macOS, so you can use it rightaway.

To install CocoaPods on your Mac, open Terminal and execute the following command:

Don’t type the sign. In books, tutorials, courses etc. that sign denotes a command that needs to be executed on the command-line, like Terminal.

CocoaPods will now install system-wide on your Mac. You may need to input your administrator password, because the command temporarily needs administrator access to install CocoaPods for the duration of the installation.

If you need to update CocoaPods to a newer version later on, you can just run again. CocoaPods will tell you when a new version is available, if you run any of its commands. It’s a good idea to keep CocoaPods up-to-date, especially around new Xcode releases.

Now that CocoaPods is installed, let’s move on!

Using Installed Pods

Now, you’ll use your brand new dependency, Alamofire.

If the Xcode project is open, close it now and open IceCreamShop.xcworkspace.

Open PickFlavorViewController.swift and add the following just below the existing import:

import Alamofire

Build and run. You’ll see no change yet but rest assured that Alamofire is now available.

Next, replace with the following:

  private func loadFlavors() {
    // 1    
    Alamofire.request(
      "https://www.raywenderlich.com/downloads/Flavors.plist",
      method: .get,
      encoding: PropertyListEncoding(format: .xml, options: 0))
        .responsePropertyList {  response in
        // 2
        guard let self = self else { return }
        
        // 3        
        guard 
          response.result.isSuccess,
          let dictionaryArray = response.result.value as? ] 
          else {
            return
        }

        // 4
        self.flavors = self.flavorFactory.flavors(from: dictionaryArray)
        
        // 5
        self.collectionView.reloadData()
        self.selectFirstFlavor()
    }
  }

Here’s the play-by-play of what’s happening in this code:

  1. You use Alamofire to create a GET request and download a plist containing ice cream flavors.
  2. To break a strong reference cycle, you use a weak reference to in the response completion block. Once the block executes, you immediately get a strong reference to so you can set properties on it later.
  3. Next, you verify the shows success and the is an array of dictionaries.
  4. Now, you set to an array of objects that creates. This is a class a “colleague” wrote for you (you’re welcome!), which takes an array of dictionaries and uses them to create instances of .
  5. Finally, you reload the collection view and select the first flavor.

Build and run. You can now choose an ice cream flavor!

Adding a Pod

You can find available Pods using the search box on the official CocoaPods site or using the Wantedly search. When you find a pod you want to add to your project, follow these steps:

Create the Podfile

You only need a single Podfile per project. The Podfile is a plain text file where you can add multiple pods.

From a terminal in the root directory of your project, run…

pod init

️ Common Issues

Please refer to these steps if you encounter issues when installing cocoapods.

On your terminal

Install ffi

Re-installing dependency

If you are having issues installing Ruby, gems, or cocoapods, try these:

Check out this stackoverflow in case you encounter even more issues.

Add dependencies to the Podfile

  • In the example below, we’ll add Alamofire and a few others:

  • Refer to the podfile documentation to see versioning options and more complex use cases.

Download and integrate the dependencies into your project

  • From a terminal in the root directory of your project, run…

  • CocoaPods currently forks the spec repo. If the pod install fails, you may need to update your current specs:

Open the Xcode workspace

  • Close the project () if you have it open and open the workspace ().
  • CocoaPods creates an additional project for all the dependencies so you need to open the from now on (which will contain your original project and the pods project).:

8 ответов

Лучший ответ

У меня та же проблема. Проверьте, какая версия Firebase установлена, когда вы используете модуль Firebase. Для меня он устанавливает старую версию 2.4.3. В документации говорится, что модуль должен установить 3.2. используя эту капсулу. Это объясняет, почему другие модули не работают, поскольку они являются частью Firebase 3. Обновление Pod также не обновляет Firebase до последней версии. Даже принудительная установка версии не работает. Кажется, не удается найти новые версии Firebase, даже если они находятся в одной спецификации.

Вот как я это решил:

  • убедитесь, что у вас установлена ​​последняя версия git
  • убедитесь, что у вас установлены cocoapods> = 1.0.0
  • удалите репозиторий стручков (запустите ) и используйте , чтобы создать новый
  • используйте следующее в своем файле pod

(используйте все, что хотите, только не используйте Firebase)

  • все должно быть установлено правильно

28

kbpontius
16 Май 2017 в 23:12

Та же проблема возникла при выполнении команды pod install .

Пожалуйста, перезапустите терминал и перейдите в свой проект Xcode, затем

Просто запустите ту же команду pod install . Firebase / Database будет успешно установлена ​​:)

1

Harshal Wani
27 Фев 2017 в 05:07

Для людей, у которых все еще есть проблемы с этим. При прямом копировании веб-сайта с пошаговым руководством по firebase строка установки выглядит так:

Хотя должно было быть:

Нет необходимости настраивать модуль, если это относится и к вам.

Magnus Wang
23 Сен 2018 в 08:30

У меня была та же ошибка, и моим решением было понизить версию до , потому что не работал так, как я ожидал. Теперь все отлично работает!

Мой :

Victor
14 Июн 2016 в 16:11

Я просто делаю следующий шаг, чтобы исправить эту ошибку:

Затем сделайте

Это работает для меня, и мой файл pod:

ОБНОВЛЕНИЕ:

Затем вы можете удалить своего мастера и переустановить cocoapods, используя следующий код:

Nitin Gohel
9 Июн 2016 в 04:51

Запуск ‘pod repo remove master’ для удаления репозитория Pods // удаляет библиотеку

Запуск ‘pod setup’ // клонирует обновленное репозиторий git для спецификаций, что занимает много времени, так как его размер превышает 300 КБ (будьте терпеливы!)

Запуск pod install // проблема решена

12

Aadi007
12 Июл 2016 в 06:10

Вы пробовали добавить

Frameworks use_frameworks!

После целевой строки ‘RandomName’

И добавление

Платформа: ios, 9.0

Перед целью ….

1

kemalony
27 Май 2016 в 14:03

Обновите Git и Cocoapods до последней версии:

Git:

Коко-моллюски:

Alex Lopez
17 Янв 2019 в 10:54

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Все про сервера
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: