user2014474 user2014474 - 5 months ago 44
iOS Question

Extracting file name from NSData

I am using bluetooth to send files along to other devices. The content sent is NSData:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.ext", button.titleLabel.text]];

NSData *Recording = [NSData dataWithContentsOfFile:myFilePath];


The file is an image. The file is received and views fine, but I would like to save it to the documents directory with the same name it had before, which is the button.titleLabel.text. When you send a file, it always has a name. How can I get it?

Answer
  • Your code

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];  
    NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.ext", button.titleLabel.text]];  
    NSData *Recording = [NSData dataWithContentsOfFile:myFilePath];
    
  • Make NSDictionary and put the filename and image data like this

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects:myFilePath,Recording  forKeys:@"fileName",@"imageData"];
    
  • Then convert the dictionary into NSData like this

    NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:dict];
    

  • After recieving the data convert the data into dictionary again and extract the imageData and the filePath

    NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];