How to save a CoreGraphics Drawing in Swift

To capture a view, you can use UIGraphicsImageRenderer and drawHierarchy:

let image = UIGraphicsImageRenderer(bounds: view.bounds).image { _ in
    view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
}

To save it in UserDefaults, you could:

if let data = image.pngData() {
    UserDefaults.standard.set(data, forKey: "snapshot")
}

To retrieve it from UserDefaults, you could:

if let data = UserDefaults.standard.data(forKey: "snapshot"), let image = UIImage(data: data) {
    ...
}

Personally, I wouldn't be inclined to store images in UserDefaults. I'd save it to persistent storage. For example, to save it into the Application Support folder you could:

do {
    let fileURL = try FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("test.png")

    try data.write(to: fileURL, options: .atomicWrite)
} catch {
    print(error)
}

    //I would recomend you to save line on touches end
     override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

        save()
    }

    func save() {

        var data : NSMutableData=NSMutableData()

        var archiver=NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(lines, forKey:"classLine")
        archiver.finishEncoding()

        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "shape")
    }


    class func loadSaved() {
        if let data = NSUserDefaults.standardUserDefaults().objectForKey("shape") as? NSData {

            var unarchiver :NSKeyedUnarchiver = NSKeyedUnarchiver(forReadingWithData: data);

            var line : Line = unarchiver.decodeObjectForKey("classLine") as Line!

        }

    }



}


class Line : NSObject {

    var start: CGPoint
    var end: CGPoint

    init(start _start: CGPoint, end _end: CGPoint ) {
        start = _start
        end = _end

    }

    func encodeWithCoder(aCoder: NSCoder) {

            aCoder.encodeCGPoint(start, forKey: "start")
            aCoder.encodeCGPoint(end, forKey: "end")

    }

    required init(coder aDecoder: NSCoder) {

        start  = aDecoder.decodeCGPointForKey("start")
        end  = aDecoder.decodeCGPointForKey("end")


 }
}