I want to simulate downloading an image file (png) and storing it in SwiftUI. How do I simply copy a file from finder into my xcode project so I can reference it for a test/demo? I want to get the raw bytes from it.
我想模拟下载图像文件(PNG)并将其存储在SwiftUI中。我如何简单地将文件从finder复制到我的Xcode项目中,以便我可以引用它进行测试/演示?我想要从中获取原始字节。
I've looked and it seems like you can copy things files into assets, but I'm not sure that will represent what I eventually want to do, which is download them and store them.
我已经看过了,似乎可以将文件复制到资产中,但我不确定这是否代表我最终想要做的事情,即下载并存储它们。
Is there any way to drag an image file into an xcode project?
有没有办法将图像文件拖到Xcode项目中?
更多回答
just drag & drop it somewhere in your Xcode's Project Navigator on the left side. Make sure to click Copy items if needed
and press Finish
.
只需将其拖放到Xcode左侧的项目导航器中的某个位置即可。如果需要,请确保单击复制项目,然后按完成。
This has nothing to do with SwiftUI
这与SwiftUI无关
You can access the “raw bytes” of an image by loading it as a UIImage. It’s not very clear which part of image downloading you want to simulate, but in general if you want to handle images as Data you should look at the UIImage class.
您可以通过将图像作为UIImage加载来访问图像的“原始字节”。不太清楚您想要模拟图像下载的哪个部分,但一般来说,如果您希望将图像作为数据处理,则应该查看UIImage类。
@loremipsum, sorry. Should I put it in xcode?
@loreipsum,对不起。我应该把它放在Xcode里吗?
Sure, but why not just drag the image? It will work. You may be meaning to ask a different question.
当然,但为什么不直接拖动图像呢?会成功的你可能想问另一个问题。
优秀答案推荐
Just as @stackish commented I clicked and dragged the png file into the project. There was a dialog message and I accepted the default settings.
就像@stackish评论的那样,我点击并将PNG文件拖到项目中。出现一条对话框消息,我接受了默认设置。
guard let path = Bundle.main.path(forResource: "myimage", ofType: "png") else {
print("Could not open file")
return
}
A pretty comfortable way is the Asset Catalog
一种非常舒适的方式是资产目录
Select the Asset Catalog in the Project Navigator.
Click on the + button at the bottom of the asset list and choose Image Set.
Use a meaningful name for the asset for example Placeholder
Drag the image from the Finder into the 1x, 2x, or 3x square according to the resolution.
In the code use
Image("Placeholder")
But why not still simpler with SF Symbols
但为什么不更简单地使用SF符号呢
Image(systemName: "photo")
.font(.largeTitle)
更多回答
我是一名优秀的程序员,十分优秀!