Saving pictures to Camera roll with iOS charts

1.5k views Asked by At

I tried to save a graph, which I created with the iOS Charts api, to the camera roll. There exists only the following function:

private func saveButton() {
    barChartView.save(to: STRING, format: ChartViewBase.ImageFormat, compressionQuality: Double)
}

Which value should I enter for "to"?

4

There are 4 answers

1
Cesar On BEST ANSWER

Try with this

let a = barChartView.save(to: "\(AppDelegate.getAppDelegate().getDocDir())/chart.png", format: BarLineChartViewBase.ImageFormat.png, compressionQuality: 1.0)

The value which you can enter for "to" is the path where the chart will be saved.

In the previous version existed 2 methods

barChartView.saveToCameraRoll()
barChartView.saveToPath(path: String, format: ChartViewBase.ImageFormat, compressionQuality: Double)

Now just exist

barChartView.save(to: STRING, format: ChartViewBase.ImageFormat, compressionQuality: Double)

I don't know what is the path to the camera roll, but maybe just change the path and could work

0
Icetime On

Finally, I found another solution:

public func saveGraph() {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}

This code is implemented into a ViewController which is called by from a PageViewController

0
Zohaib On

You can use the same function which is use by Charts.

     let image = chartView.getChartImage(transparent: false)
     UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
0
Anirudhh On

The answers above are all correct, however please make sure that when you do run code that saves to your camera roll, such as:

    let graphImage = myGraph.getChartImage(transparent: false)
    UIImageWriteToSavedPhotosAlbum(graphImage!, nil, nil, nil)

That you have added the requirements of NSPhotoLibraryAddUsageDescription("Privacy - Photo Library Additions Usage Description", this is now required since iOS 11) and the NSPhotoLibraryUsageDescription(“Privacy - Photo Library Usage Description”) with the string text that you would like to display to the user (to explain why you need to save to the camera roll).

These requirements should be added to your Info.plist file, in your Xcode project.

Otherwise your app will crash when you run any code that saves an item to your camera roll.

I have attached a screenshot to show how this should look:

Info.plist Photo Library Usage Description and Photo Library Additions Usage Description

You can find more information about the Info.plist requirements here.