我有一个应用程序,可以保存创建的用户事件,其中包含标题、日期和图像以供个人使用。 它与核心数据一起存储,因此图像被存储为数据。 我有一个共享应用程序组,我正在尝试将文件写入其中,然后在实时活动中显示它。文件的写入似乎已完成,但实时活动从未启动,并且我在创建实时活动时收到错误。
当我将 IF 语句保留在 View 中,但将语句中的图像更改为资产时,它实际上呈现了图像,因此看起来将数据获取到 UIImage 的功能也有效。但是当我将 let 图像设置为 if 语句内的图像时,它不会创建实时活动。
非常感谢您在这里做出的贡献。 (这里对初学者知识表示歉意。开始:))
这是Live Activity和函数的创建: `
class EventModel: ObservableObject {
@Published var event: EventEntity
var liveActivity: Activity<EventAttributes>? = nil
func startLiveActivity() {
let _ = saveImage(data: (event?.image)!)
let liveEvent = LiveActivityEvent(title: (event?.title)!, date: (event?.date)!)
let attributes = EventAttributes(event: liveEvent)
do {
liveActivity = try Activity.request(attributes: attributes, contentState: EventAttributes.ContentState())
} catch {
print(error.localizedDescription)
}
}
}
func saveImage(data: Data) -> Bool {
guard let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "AppGroupIdentifier") else {
fatalError("could not get shared app group directory.")
}
do {
try data.write(to: groupURL.appendingPathComponent("LiveActivityPhoto"))
return true
} catch {
print(error.localizedDescription)
return false
}
}
func getSavedImage(named: String) -> UIImage? {
if let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "AppGroupIdentifier") {
return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
}
return nil
}
`
这是实时活动视图 `
struct LiveActivityView: View {
var context: ActivityViewContext<EventAttributes>
var body: some View {
HStack {
if let image = getSavedImage(named: "LiveActivityPhoto") {
Image(uiImage: image)
}
}
}
}
`
我找到了基于应用程序组的解决方案
为主目标和小部件添加
App Group
功能(项目 - >目标 - >签名和功能选项卡 - >找到“+”号。应用程序组应该具有相同的名称
然后你可以像这样将任何图像保存到目标URL
private func uploadImage() {
guard var destination = FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: “group.YOUR_GROUP_NAME")
else { return }
destination = destination.appendingPathComponent("imageName")
let image = UIImage(named: "kopiumTest")!
if let imageData = image.jpegData(compressionQuality: 0.5) {
try? imageData.write(to: destination)
}
}
然后您就可以使用刚刚保存的图像了
@ViewBuilder var uploadIcon: some View {
let imageContainer = FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: "group.YOUR_GROUP_NAME")?
.appendingPathComponent("imageName"),
let uiImage = UIImage(contentsOfFile: imageContainer.path()) {
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 50, height: 50)
} else {
Text("Not found")
}
}
干杯