无法使用 UIActivityViewController 来分享 twitter 和 facebook 的 url

问题描述 投票:0回答:2

无法在 Twitter 和 Facebook 中分享网址,这是我的代码:

- (IBAction)btnSharePressed:(UIButton *)sender
{

    UIImage *shareImage = [UIImage imageNamed:@"toolBar.png"];
    NSString *shareTitle = @"Share Title";
    NSURL *shareUrl = [NSURL URLWithString:@"http://www.google.com"];

    NSArray *Items = @[shareUrl,shareImage,shareTitle];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc]
                                              initWithActivityItems:Items
                                              applicationActivities:nil];

    [activityVC setValue:shareTitle forKey:@"subject"];

    [self presentViewController:activityVC animated:YES completion:nil];
}

仅在 Twitter 和 Facebook 帖子撰写框中获取 shareTitle 内容,缺少 shareUrl 内容,图像渲染完美。请让我知道我错在哪里?预先感谢。

更新

我知道 url 的图像与我要附加的图像重叠,任何人都可以帮助我如何显示带有文本链接的 url,而不是图像中转换的 url 吗?

iphone ios7 uiactivityviewcontroller
2个回答
1
投票

代码没有问题,并且共享提供的所有详细信息,

我猜你的问题是你没有在共享弹出窗口中显示所有内容,因为图像和网址显示为owrapped

enter image description here


0
投票
class Test {

//     Sorry if this is a bit irrelevant. I've struggled to share UIImage to Instagram with UIActivityViewController. Passing UIImage to the array of items worked well for Twitter, Facebook. For Instagram it worked almost well but option to post Story returned an error "Something went wrong"
//     I've tried to save image to temporary storage on device, and put URL to that local image into the array of items. It worked but it was taking 4-5 seconds to load.. And that frustrated me A LOT.
//     Turned out I was saving image as .jpeg and chose incorrect place to store it, after saving file to documents directory as png and feeding that link to array of items solved the problem.
//     Sorry if code is not ideal because it's from a scratch SwiftUI project, but that worked perfectly for me
//     I've lost 3.5 hours on that so I decided to share to Ease the pain of others
//     Note: code contains unnecessary calls such as DispatchQueue.main.async - you can remove them


    import SwiftUI

    struct SheetOverlayView: View {
        let viewModel: SheetOverlayViewModel
        @State private var shareItem: ShareItem?

        var body: some View {
            VStack(spacing: 20) {
                Image(uiImage: viewModel.image)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .cornerRadius(20)
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color.gray, lineWidth: 2)
                    )
                    .padding()

                Text(viewModel.title)
                    .font(.headline)
                    .multilineTextAlignment(.center)

                Text(viewModel.subtitle)
                    .font(.subheadline)
                    .foregroundColor(.gray)
                    .multilineTextAlignment(.center)

                Button(action: {
                    prepareToShare()
                }) {
                    Text("Share")
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                }
                .padding(.horizontal)

                Spacer()
            }
            .padding()
            .sheet(item: $shareItem) { item in
                if FileManager.default.fileExists(atPath: item.url.path) {
                    ActivityView(activityItems: [item.url])
                } else {
                    Text("Failed to load content.")
                }
            }
        }

        private func prepareToShare() {
            print("Preparing to share image...")
            saveImageToFile { url in
                guard let url = url, FileManager.default.fileExists(atPath: url.path) else {
                    print("File not ready or does not exist.")
                    return
                }
                DispatchQueue.main.async {
                    print("File exists. Ready to share: \(url)")
                    shareItem = ShareItem(url: url)
                }
            }
        }

        private func saveImageToFile(completion: @escaping (URL?) -> Void) {
            DispatchQueue.global(qos: .userInitiated).async {
                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                let imageFileURL = documentsDirectory.appendingPathComponent("sharedImage.png")

                guard let imageData = viewModel.image.pngData() else {
                    DispatchQueue.main.async { completion(nil) }
                    return
                }

                do {
                    try imageData.write(to: imageFileURL)
                    DispatchQueue.main.async { completion(imageFileURL) }
                } catch {
                    print("Error writing file: \(error.localizedDescription)")
                    DispatchQueue.main.async { completion(nil) }
                }
            }
        }
    }

    // Identifiable ShareItem to manage sheet presentation
    struct ShareItem: Identifiable {
        let id = UUID()
        let url: URL
    }

    // View for sharing
    struct ActivityView: UIViewControllerRepresentable {
        let activityItems: [Any]
        let applicationActivities: [UIActivity]? = nil


        func makeUIViewController(context: Context) -> UIActivityViewController {
            UIActivityViewController(activityItems: activityItems, applicationActivities: applicationActivities)
        }

        func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
    }

    // Dummy view model for preview
    struct SheetOverlayViewModel {
        let image: UIImage
        let title: String
        let subtitle: String
        let hashtag: String
    }

    #Preview {
        SheetOverlayView(
            viewModel: SheetOverlayViewModel(
                image: UIImage(systemName: "person.crop.circle")!,
                title: "Title",
                subtitle: "Subtitle",
                hashtag: "hashtag"
            )
        )
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.