Как бороться с предупреждением об отсутствии файла Xcode в репозитории Git?
Я использую GIT для управления исходным кодом в моем проекте Xcode. После обновления библиотеки Cocopod я начал получать предупреждения, подобные следующим:
File:///Users/NinjaDev/Development/Xcode/NinjaApp/Pods/Alamofire/Source/Download.swift: предупреждение: Отсутствует файл: /Users/NinjaDev/Development/Xcode/NinjaApp/Pods/Alamofire/Source/Download.swift отсутствует в рабочей копии
Библиотека изменилась, так что файла Download.swift больше нет. Я зафиксировал проект и сделал чистку и перестройку, но все еще получаю сообщение об ошибке. Я предполагаю, что репозиторий не знает, что он был удален, но я не очень хорошо знаком с внутренней работой Git. как правильно это исправить и предотвратить повторение этого?
Изменить: по предложению Aspirin2D, вот статус git. В журнале git не было ничего необычного.
Статус Git
РЕДАКТИРОВАТЬ 2: Я понял, что произошло. Когда я зафиксировал в Xcode, файлы, которые я удалил, по умолчанию должны были быть сняты с проверки. Пока я возился с проблемой, я снова открыл меню фиксации, и, конечно же, это была просто куча непроверенных файлов. Проверьте их и снова зафиксируйте предупреждения. Почему Xcode по умолчанию не проверяет некоторые файлы?
Swift — Unable to open file in target Xcode 10
I am trying to run Aplication which I have downloaded from GitHub.
When I run get error unable to open file in target, I have Xcode 10.
I already searched for solution and get this one.
I had the same problem, but in Xcode 6.1.1 — what fixed it for me was to change the configuration file setting to None for the two Pods-related targets, then run pod install again.
The configuration file setting is found by selecting the project (not the target) and then the Info tab.
But cant find configuration file location.
16 Answers 16
In File -> Project setting -> select Legacy Build System
Make sure you have opened .xcworkspace file and pod installed properly.
A solution I found to work for me was
Inside the project root directory
Delete the following files. Ensure you have copied the contents of Podfile.
- Podfile
- Podfile.lock
- Pods Folder
Open your .xcodeproj using Xcode or using terminal command
Inside Xcode, locate the «Pods» folder which should contain something along the lines of.
Delete those references and select «move to trash» when prompted.
Now run the following:
Open your Podfile and paste in your previously copied old Podfile that was deleted earlier.
run the following command:
In terminal open Xcode again with the following command
Note: that I opened the xcworkspace file NOT the xcodeproj file.
At this point for me I was able to compile my code as normal without having to change back to the Legacy Build System.
Почему git не открывает файлы на swift
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Swift Programming Language
Architecture | Build |
---|---|
macOS | x86_64 |
Ubuntu 18.04 | x86_64 |
Ubuntu 20.04 | x86_64 |
Ubuntu 20.04 | AArch64 |
Ubuntu 22.04 | x86_64 |
Ubuntu 22.04 | AArch64 |
CentOS 7 | x86_64 |
Amazon Linux 2 | x86_64 |
Amazon Linux 2 | AArch64 |
Swift Community-Hosted CI Platforms
OS | Architecture | Build |
---|---|---|
Ubuntu 20.04 | wasm32 | |
Android | ARMv7 | |
Android | AArch64 | |
Windows 2019 (VS 2017) | x86_64 | |
Windows 2019 (VS 2019) | x86_64 |
Welcome to Swift
Swift is a high-performance system programming language. It has a clean and modern syntax, offers seamless access to existing C and Objective-C code and frameworks, and is memory safe by default.
Although inspired by Objective-C and many other languages, Swift is not itself a C-derived language. As a complete and independent language, Swift packages core features like flow control, data structures, and functions, with high-level constructs like objects, protocols, closures, and generics. Swift embraces modules, eliminating the need for headers and the code duplication they entail.
To learn more about the programming language, visit swift.org.
Contributing to Swift
Contributions to Swift are welcomed and encouraged! Please see the Contributing to Swift guide.
To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone.
To give clarity of what is expected of our members, Swift has adopted the code of conduct defined by the Contributor Covenant. This document is used across many open source communities, and we think it articulates our values well. For more, see the Code of Conduct.
If you are interested in:
- Contributing fixes and features to the compiler: See our How to Submit Your First Pull Request guide.
- Building the compiler as a one-off: See our Getting Started guide.
- Building a toolchain as a one-off: Follow the Getting Started guide up until the «Building the project» section. After that, follow the instructions in the Swift Toolchains section below.
We also have an FAQ that answers common questions.
Swift toolchains are created using the script build-toolchain. This script is used by swift.org’s CI to produce snapshots and can allow for one to locally reproduce such builds for development or distribution purposes. A typical invocation looks like the following:
where $BUNDLE_PREFIX is a string that will be prepended to the build date to give the bundle identifier of the toolchain’s Info.plist . For instance, if $BUNDLE_PREFIX was com.example , the toolchain produced will have the bundle identifier com.example.YYYYMMDD . It will be created in the directory you run the script with a filename of the form: swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz .
Beyond building the toolchain, build-toolchain also supports the following (non-exhaustive) set of useful options:
- —dry-run : Perform a dry run build. This is off by default.
- —test : Test the toolchain after it has been compiled. This is off by default.
- —distcc : Use distcc to speed up the build by distributing the C++ part of the swift build. This is off by default.
- —sccache : Use sccache to speed up subsequent builds of the compiler by caching more C++ build artifacts. This is off by default.
More options may be added over time. Please pass —help to build-toolchain to see the full set of options.
Installing into Xcode
On macOS if one wants to install such a toolchain into Xcode:
-
Untar and copy the toolchain to one of /Library/Developer/Toolchains/ or
The script also generates an archive containing debug symbols which can be installed over the main archive allowing symbolication of any compiler crashes.
- Specify the local toolchain for Xcode’s use via Xcode->Toolchains .
Make sure you are using the correct release of Xcode.
If you have changed Xcode versions but still encounter errors that appear to be related to the Xcode version, try passing —clean to build-script .
When a new version of Xcode is released, you can update your build without recompiling the entire project by passing —reconfigure to build-script .
Be sure to look at the documentation index for a bird’s eye view of the available documentation. In particular, the documents titled Debugging the Swift Compiler and Continuous Integration for Swift are very helpful to understand before submitting your first PR.
XCode не находит Swift файл заголовочного файла в некоторых файлах
У меня есть проблема в моем приложении iOs с XCode. Он был закодирован в Objective-C, и теперь я работаю над переносом файлов в Swift один за другим. Код делится между членами команды с системой управления версиями (git).
Я начал с основных классов, и я продолжаю так:
-
Я пишу новый класс в файле Swift, например. MyClass.swift(с ключевым словом @objc prefix)
Я заменяю #import «MyClass.h» на @class MyClass; в заголовочных файлах
Я добавляю #import «MyProject-Swift.h» в файлы реализации (.m), нуждающиеся в этом
Я удаляю файлы MyClass.h и MyClass.m
Я очищаю и создаю проект
Этот процесс работал несколько раз, но по некоторым причинам некоторые #import «MyProject-Swift.h» не работают, и я получаю ошибку: Файл MyProject-Swift.h не найден.
В соответствии с различными файлами, вызывающими проблему, иногда Ctrl + Click открывает файл «MyProject-Swift.h», иногда нет (независимо от «не найденной ошибки» ).
Но файл существует, и в нем присутствует переведенный код Swift.
Еще одна вещь, очень странная, я попытался воссоздать новые .h и .m файлы из тех, которые используют материал #import «MyProject-Swift.h» и имеет проблему, и после этого он работает (иногда нет, и я получаю другие ошибки)!
Как это работает в некоторых случаях, я действительно не понимаю, почему он вызывает проблемы для других случаев. Конечно, я искал среди десятков тем, но не нашел никого с той же проблемой.
Возможно, это проблема с настройками XCode или из-за разных версий XCode между разработчиками команд?
Отредактировано:
Я завершу описание проблемы с другой точкой зрения.
У меня есть проект в рабочем состоянии: использует некоторые из моих новых файлов Swift, он строит и работает хорошо (некоторые файлы Objective-C используют файлы Swift).
Я знаю определенный файл .m с проблемой:
-
Я добавляю #import «MyProject-Swift.h» в начале, ничего больше
XCode говорит, что Файл MyProject-Swift.h не найден, Ctrl + Click не работает, и проект не будет компоноваться
Но если я нажму на кнопку с четырьмя квадратами (вверху слева от редактора), в отображаемом меню у меня есть «Включает», под ним отображается «MyProject-Swift.h», MyProject-Swift.h «открывает файл!
Замена #import «MyProject-Swift.h» на #import <MyProject-Swift.h> ничего не изменит.
У меня также есть этот случай: Ctrl + Click открывает «MyProject-Swift.h», но XCode говорит, что «MyProject-Swift.h» не найден (он также не будет построен).
Я, наконец, придумал решение самостоятельно: файл project.pbxproj был искажен после некоторого слияния git, я думаю. Некоторые файлы проекта дважды ссылались на этот файл, поэтому я удалил те, которые, как я думал, были плохими (возможно, случайно выбранный ближе к истине).
Теперь он работает как шарм.
Фактически это не повлияло на проект, пока я не попытался перенести файлы в Swift!
Было бы неплохо иметь инструмент или функцию в XCode для reset этого файла project.pbxproj для текущих вещей, которые у нас есть.
на основе that asumption qaru.site/questions/711497/. Я решил эту проблему в этом простом
Найдите объектный файл C, в котором компилятор утверждает, что он не может найти файл YourProject-Swift. Удалите его файл из проекта, а затем добавьте.
После этого мой проект успешно скомпилирован и запущен
Добавьте в проект заголовочный файл с именем [MyProjectName] -Bridging-Header.h.. Это будет единственный файл заголовка, в который вы импортируете любой код Objective-C, который вы хотите Быстрый код для доступа.
В настройках сборки проекта найдите Swift Compiler — Code Generation, а рядом с Objective-C Bridging Header добавьте путь к вашему заголовочному файлу мостов из корневой папки проектов. Таким образом, это может быть MyProject/MyProject-Bridging-Header.h или просто MyProject-Bridging-Header.h, если файл находится в корневой папке проекта.
Вам нужен только один заголовок моста. Добавьте в этот файл свои #import-инструкции, и теперь ваши классы будут доступны в вашем Swift-коде без каких-либо дополнительных операторов импорта.
Если у вас есть две цели, и вы продолжаете получать компиляцию/семантические ошибки для недавно отредактированных быстрых файлов, используемых в коде ObjC, это может быть проблемой —
У вас есть два файла <ProjectName>-swift.h . Как в моем случае:
MyProject-swift.h и MyProjectSandbox-swift.h
Это файлы со всеми быстрыми классами и методами.
(Они открываются, когда вы нажимаете Command на любом быстром классе из кода Obj-C).
Итак, я работаю над целью Sandbox .
Я обнаружил, что, когда я вносил изменения в быстрые файлы и чистую сборку, обновлялся только MyProjectSandbox-swift.h .
Но основная проблема заключалась в том, что код ObjC ссылался на файл MyProject-swift.h , который не обновляется, поскольку я только восстанавливал цель (песочницу), над которой я работал.
TL; DR;
Итак, решение состоит в том, чтобы убедиться, что вы очищаете и перестраиваете BOTH свои цели, чтобы оба ( MyProject-swift.h и MyProjectSandbox-swift.h ) обновлялись последним быстрым кодом и классами.
Это обновит оба файла, и ваш код ObjC не покажет никаких неулокальных ошибок компиляции для быстрых файлов.