0

I am fairly new to iOS development, and am unable to store an SVG image in the documents directory of my app. I have access to the raw data and would like to store this in SVG format

The raw data is in NSData format.

NSData *rawData = [[NSData alloc] initWithBytes:ptr length:size];

rawData has the dowloaded file, please help me save this as an SVG. Any help appreciated, also I have been doing this for less than a week, sorry for any mistakes.

rexGibbs
  • 1
  • 4
  • Possible duplicate of [The easiest way to write NSData to a file](https://stackoverflow.com/questions/679104/the-easiest-way-to-write-nsdata-to-a-file) – Smartcat Oct 24 '19 at 04:39
  • @Smartcat Will just writing the NSData work ? – rexGibbs Oct 24 '19 at 04:42
  • Sure, if the NSData is already in the encoding you desire for your file (typically UTF8). The resulting file should just be an XML text file (in UTF8) if that's what's represented in the NSData that you have. Remember, SVG is simply an XML grammar. (Back in the day, I actually wrote the first SVG XML parser to get SVG approved by the W3C. :) – Smartcat Oct 24 '19 at 04:46
  • Oh, so you actually are a smart cat :p I'll try doing it. Thanks a lot good sir. – rexGibbs Oct 24 '19 at 04:55
  • Ha! No, I just used to have some rather smart cats that would play fetch, shake hands on command, etc... I picked the alias to memorialize them. They had a rather low impression of me. :) If you get further stuck with this, my profile has a slack link for where to find me for chat. – Smartcat Oct 24 '19 at 05:06

1 Answers1

0

yeah, do this:

- (NSString *)writeDataToDocuments:(NSData *)data withFilename:(NSString *)filename {
  NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  NSString *filePath = [[NSString alloc] initWithString: [docsPath stringByAppendingPathComponent:filename]];
  [data writeToFile:filePath atomically:YES];
  return filePath;
}

the file path returned is where the SVG is now stored

so in your case it's

NSData *rawData = [[NSData alloc] initWithBytes:ptr length:size];
NSString *fileLocationString = [self writeDataToDocuments:rawData withFilename:@"example.svg"];

and now it's saved and you have the file path

Larry Pickles
  • 4,615
  • 2
  • 19
  • 36