Friday, June 21, 2013

NSNetService dataFromTXTRecordDictionary example in Objective C (iOS).


NSNetService dataFromTXTRecordDictionary

Returns an NSData object representing a TXT record formed from a given dictionary.

+ (NSData *)dataFromTXTRecordDictionary:(NSDictionary *)txtDictionary

Parameters
txtDictionary
A dictionary containing a TXT record.

Return Value of [NSNetService dataFromTXTRecordDictionary]
An NSData object representing TXT data formed from txtDictionary. Fails an assertion if txtDictionary cannot be represented as an NSData object.
NSNetService dataFromTXTRecordDictionary example.
NSImage *original = [NSImage imageNamed:NSImageNameComputer];
                [original setSize:NSMakeSize(10.0f, 10.0f)];
                NSData *image = [original TIFFRepresentation];
                NSBitmapImageRep *imageRep = [NSBitmapImageRep 
imageRepWithData:image];
                NSData *finalData = [imageRep representationUsingType:NSPNGFileType 
properties:nil];
                NSDictionary *txtRecord = [NSDictionary 
dictionaryWithObject:finalData forKey:@"image"];
                NSData *data = [NSNetService dataFromTXTRecordDictionary:txtRecord];
                if (data)
                        NSLog(@"Data is not nil!");
                [netService setTXTRecordData:data];


Example of [NSNetService dataFromTXTRecordDictionary].
// Open a stream to the server, finding the server via Bonjour.  Then configure
// the stream for async operation.

//here's the tweak.
//original code looked like -
//self.netService = [[[NSNetService alloc] initWithDomain:@"local." type:@"_x-SNSUpload._tcp." name:@"Test"] autorelease];

self.netService = [[[NSNetService alloc] initWithDomain:@"10.212.19.121" type:@"_smb._tcp." name:@"lanmanserver"] autorelease];

assert(self.netService != nil);

NSDictionary *newDict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"domain\\username",@"password",@"C:\\Documents and Settings\\username\\Desktop\\test%20sharing",nil] forKeys:[NSArray arrayWithObjects:@"u",@"p",@"path",nil]];

[self.netService setTXTRecordData:[NSNetService dataFromTXTRecordDictionary:newDict]];

NSNetService dataFromTXTRecordDictionary example.
NSDictionary *txt = [NSDictionary dictionaryWithObjectsAndKeys:
    [@"1" dataUsingEncoding:NSUTF8StringEncoding], @"txtvers",
    [@"131073" dataUsingEncoding:NSUTF8StringEncoding], @"iTSh Version",
    [@"196610" dataUsingEncoding:NSUTF8StringEncoding], @"Version",
    nil];

NSData *txtData = [NSNetService dataFromTXTRecordDictionary:txt];

[bonjourServer setTXTRecordData:txtData];

End of NSNetService dataFromTXTRecordDictionary example article.