使用UIActivityViewController共享图像

时间:2017-07-12 05:01:06

标签: ios uiactivityviewcontroller

我与UIActivityViewController共享,但它与不同的文件名(随机名称)共享。当我与照片应用程序共享时,它的共享图像与其真实姓名。我的问题是: 如何使用UIActivityViewController与其名称共享图像?

答案: 大家好,

是的,我得到了答案。 首先将图像保存在docuementDirectory中,然后共享图像链接。请确保共享图像链接(在docuement目录中保存的图像)而不是图像。

@IBAction func shareImage(_ sender:UIButton){

    var selectedImageArrayToShare:Array<NSURL> = [NSURL]()
    selectedImageArrayToShare.append(saveActivityControllerImage())
   let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: selectedImageArrayToShare as [Any], applicationActivities: nil)
    self.present(activityViewController, animated: true, completion: nil)
}


func saveActivityControllerImage() -> NSURL {

    var name:String=selectedPhotoName!.capitalized
    print(name.components(separatedBy: ".").last as Any)
    if name.components(separatedBy: ".").last!.lowercased() != "png" {
        name = name.replacingOccurrences(of: ".\(name.components(separatedBy: ".").last!)", with: ".jpg")
    }
    else {
        name = name.replacingOccurrences(of: ".\(name.components(separatedBy: ".").last!)", with: ".png")
    }
    let urlString : NSURL = getDocumentDirectoryPath(fileName: name)
    print("Image path : \(urlString)")
    if !FileManager.default.fileExists(atPath: urlString.absoluteString!) {
        do {
            var isSaved : Bool = false
            print(urlString.pathExtension as Any)
            if urlString.pathExtension?.lowercased() == "png" {
                isSaved = ((try  UIImagePNGRepresentation(photoPreviewImageView.image!)?.write(to: urlString as URL, options: Data.WritingOptions.atomic)) != nil)
            }
            else {
                isSaved = ((try  UIImageJPEGRepresentation(photoPreviewImageView.image!, 1.0)?.write(to: urlString as URL, options: Data.WritingOptions.atomic)) != nil)
            }

            if (isSaved) {
                return urlString

            } else {
                return NSURL.fileURL(withPath: "Blank") as NSURL
            }
        } catch {
            return NSURL.fileURL(withPath: "Blank") as NSURL
        }
    }
    return urlString
}

func getDocumentDirectoryPath(fileName:String) - &gt; NSURL {

    let paths:NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
    let docuementDir:NSString = paths.object(at: 0) as! NSString
    return NSURL.fileURL(withPath: docuementDir.appendingPathComponent("NameIt/\(fileName)")) as NSURL
}

1 个答案:

答案 0 :(得分:0)

像这样分享

 let activityItem: [AnyObject] = [self.imageView.image as! AnyObject]

        let avc = UIActivityViewController(activityItems: activityItem as [AnyObject], applicationActivities: nil)

        self.presentViewController(avc, animated: true, completion: nil)