【问题标题】:Save image to library from URL, rename, and share it using Swift将图像从 URL 保存到库,重命名并使用 Swift 共享它
【发布时间】:2017-01-13 19:07:33
【问题描述】:

我想将图像从我自己的 iOS 应用程序分享到 Instagram,并且我在整个项目中使用 Kingfisher 来下载和缓存图像并在 UIImageViews 中显示它们,但这次我想做一些不同的事情。

基本上,我从 API 收到带有图片网址的响应,我想要

  1. 使用 URL 将图像下载到库中

对于 Objective-C 使用有很多关于此的问题

 UIImageWriteToSavedPhotosAlbum 

但我使用的是 Swift。

  1. 使用 .igo 扩展名重命名(instagram 独有)

不确定如何处理,取决于数字 1。

  1. 然后我可以通过类似的方式分享它

            let image = UIImage(named: "downloadedImage")
            let objectsToShare: [AnyObject] = [ image! ]
            let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
            activityViewController.popoverPresentationController?.sourceView = self.view
    
    
            activityViewController.excludedActivityTypes = [ UIActivityTypeAirDrop, UIActivityTypePostToFacebook ]
    
    
            self.presentViewController(activityViewController, animated: true, completion: nil)
    

或者我可以使用 Instagram 挂钩:

 instagram://library?LocalIdentifier=\(localID)

这方面的文档对于 Swift 来说特别稀缺。我该怎么办?我只需要朝着正确的方向前进。

【问题讨论】:

  • 一定要存到相册,还是直接存到本地存储文件夹?
  • @TheValyreanGroup 我不知道该怎么做。只要我可以重命名图像的扩展名,这也可以工作
  • 我刚刚发布了一个希望对您有所帮助的答案。

标签: ios swift swift2


【解决方案1】:

听起来您已经知道如何使用 Kingfisher 并从 URL 中检索 UIImage。所以我要提供的是将图像保存到文档目录并检索它以共享的信息。

检索正确的目录 URL

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

将图像保存到该目录

func saveImage (image: UIImage, filename: String ){
    print("Saving image with name \(filename)")
    if let data = UIImagePNGRepresentation(image) {
        let fullURL = getDocumentsDirectory().appendingPathComponent(filename)
        try? data.write(to: fullURL)
    }
}

从目录中检索图像

func loadImageFromName(name: String) -> UIImage? {
    print("Loading image with name \(name)")
    let path = getDocumentsDirectory().appendingPathComponent(name).path

    let image = UIImage(contentsOfFile: path)

    if image == nil {

        print("missing image at: \(path)")
    }
    return image
}

分享图片

func share(shareText shareText:String?,shareImage:UIImage?){
   var objectsToShare = [AnyObject]()
   if let shareTextObj = shareText{
      objectsToShare.append(shareTextObj)
   }
   if let shareImageObj = shareImage{
      objectsToShare.append(shareImageObj)
   }

   if shareText != nil || shareImage != nil{
      let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
      activityViewController.popoverPresentationController?.sourceView = self.view

      present(activityViewController, animated: true, completion: nil)
   }else{
     print("There is nothing to share")
   }
}

如何使用

let img: UIImage = UIImage() // Replace this with your image from your URL
saveImage(image: img, filename: "newImage.igo") //This is where you change your extension name

let newImage: UIImage = loadImageFromName(name: "newImage.igo") //Retrieve your image with the correct extension

share(shareText: "Image going to Instagram", shareImage: newImage) //Present Activity VC.

正如 DFD 指出的那样,您可以从共享 VC 中排除某些项目,只允许您需要的内容。

【讨论】:

  • 我最终稍微更改了代码,使用来自 Kingfisher 的 ImageDownloader 和 Instagram 挂钩进行发布,但执行的流程与您在此处解释的流程几乎相同。
【解决方案2】:

在我的导航控制器中,我将 UIBarButtonItem 设置为系统项“操作”。然后我创建了以下 IBAction 代码:

@IBAction func shareImage(_ sender: UIBarButtonItem) {
    let context = CIContext()
    let final = context.createCGImage(imgFinished, from: imgFinished.extent)
    let shareImage = UIImage(cgImage: final!)
    let vc = UIActivityViewController(activityItems: [shareImage], applicationActivities: [])
    vc.excludedActivityTypes =  [
        UIActivityType.airDrop,
        UIActivityType.assignToContact,
        UIActivityType.addToReadingList,
        //UIActivityType.copyToPasteboard,
        //UIActivityType.mail,
        //UIActivityType.message,
        //UIActivityType.openInIBooks,
        //UIActivityType.postToFacebook,
        //UIActivityType.postToFlickr,
        UIActivityType.postToTencentWeibo,
        //UIActivityType.postToTwitter,
        UIActivityType.postToVimeo,
        UIActivityType.postToWeibo,
        UIActivityType.print,
        //UIActivityType.saveToCameraRoll
    ]
    present(vc,
            animated: true,
            completion: nil)
    vc.popoverPresentationController?.sourceView = self.view
    vc.completionWithItemsHandler = {(activity, success, items, error) in
    }
}

excludedActivityTypes 列表是可用 UIActivityTypes 的完整/详尽列表,该列表从代码完成或命令单击 UIActivity 类型并遍历生成的结构中收集。我取消注释我希望排除的那些 - 但将它们保留以供将来快速参考。这将为您提供所需的弹出窗口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-09
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 2016-06-16
    • 1970-01-01
    相关资源
    最近更新 更多