how to send images via bluetooth in iphone programming? - iphone

I am some NSStrings, and I am just joining them and making a single NSString, then I am converting that single NSString to NSData and sending via bluetooth to other iphone
but now I have to send image with above data,
how can I achieve such concept ?
but I want to send single NSData (UIImage+NSString), how can I ????

a tutorial on how to program Bluetooth data transfer on the iPhone is here:
http://www.devx.com/wireless/Article/43502/1954
The essential part you're looking for is here:
-(IBAction) btnSend:(id) sender
{
//---convert an NSString object to NSData---
NSData* data;
NSString *str = [NSString stringWithString:txtMessage.text];
data = [str dataUsingEncoding: NSASCIIStringEncoding];
[self mySendDataToPeers:data];
}
- (void) mySendDataToPeers:(NSData *) data
{
if (currentSession)
[self.currentSession sendDataToAllPeers:data
withDataMode:GKSendDataReliable
error:nil];
}
Good luck with it!

I would recommend sending them in separate packets since an image could be quite large (send the image itself in multiple packets). But if you really want to do it all at once, try wrapping them in an NSDictionary. Encode the dictionary into NSData, and send it off.
Something like the following would work.
NSDictionary *myDict = //whatever your dict should hold here...
NSMutableData *packet = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:packet];
[archiver encodeObject:myDict forKey:#"SomeKey"];
[archiver finishEncoding];

Related

Saving Twitter Streaming APIs results

Hi all so after a lot of hassle I managed to finally work my way around achieving and delimiting the JSON returned by Twitter Streaming APIs. How do i store the data returned by [NSJSONSerialization JSONObjectWithData:options:error:] into an array in appending
mode???
Here are the codes
To call the Streaming API
self.twitterConnection = [[NSURLConnection alloc] initWithRequest:signedReq delegate:self startImmediately: NO];
and in the delegate method (which is did receive data method)
NSError *parseError = nil;
self.dataSource=[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:&parseError];
What i want to do is to store this NSJSONSerialized output in a static Array(preferably in append mode) so that i can pass it to table view for display. how do i go about it?
Thanks in Advance
EDIT
`self.dataSource1=[[NSMutableArray alloc]init];
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
string = [NSString stringWithFormat:#"[%#]", [string
stringByReplacingOccurrencesOfString:#"\r\n" withString:#","]];
NSError *parseError = nil;
self.dataSource =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:&parseError];
[self.dataSource1 addObjectsFromArray:self.dataSource];`
Use -[NSMutableArray addObjectsFromArray:] to add objects to a mutable array.
Based on your comment, it looks like you're recreating self.dataSource1 every time you get data in didReceiveData. You should only create the object once before sending the request.

Convert NSData to JSON

I have a NSData object, i need to convert it a NSDictionary object.
NSData *data = ....;
Now i need to convert this to a NSDictionary, How can i do this programatically ?
note: After i save the NSData to the NSDictionary i should be able to access key value pairs of the NSDictionary.
I don't have a code to demonstrate my workings so far, I have only created the NSData object, and have no clue to continue :)
You can subclass MKNetworkOperation and override the responseJSON method with the following:
-(id) responseJSON
{
NSString *rawJSON;
id jsonValue = nil;
if ((rawJSON = [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding]) != nil) {
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if ((jsonValue = [jsonParser objectWithString:rawJSON]) == nil) {
NSLog(#"This string doesn't seem to be JSON: '%#'\nraw Data : '%s'", rawJSON, (char *)[[self responseData] bytes]);
return [self responseString];
}
}
else {
NSLog(#"This data doesn't seem to be an UTF8 encoded string: %#", [self responseData]);
return [self responseString];
}
return jsonValue;
}
Please check this link of stack overflow, I have already consumed the JSON services, it will help you a lot. All of the coding is there.
JSON Data Conversion
And here is the tutorial with sample project
JSON Parse Tutorial
Hope you would find it helpful
I highly recommend invoking SBJSON framework, it saved my time for many times, exactly finished my work and easily to use. You don't need to know the details of the conversion algorithm, just download and invoke it.
You might want to download it from here, then follow this tutorial to get your things done.

Passing archived Data through a sharedURL

I currently have two somewhat similar apps and was looking into a way to share data across the two apps. I set up a shared url and everything and can jump from one app to the other without any problem. The problem arises when I try to pass data through the url. I have a class in both apps that are identical to one another and am relying on a NSKeyedArchiver and decoder for the encoding of them and decoding as well as encoding them in strings to pass along the url.
Having access to both sides I know that the data passed from app 1 to app 2 is untainted and arrives just as app 1 encoded it. But I can't seem to decode the data on the other side!
I encode it here:
NSURL* app2=[NSURL URLWithString:#"app2://"];
if ([[UIApplication sharedApplication] canOpenURL:app2]) {
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:[tableHelper objectAtIndex:[indexPath section]]forKey:#"TempData" ];
[archiver finishEncoding];
NSString* tmp=[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding ] autorelease];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"app2://%#",[tmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
[data release];
[archiver release];
}
I then decode it as such:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
if (!url) {
return NO;
}
NSString *URLString = [url absoluteString];
NSString* dataString=[[URLString componentsSeparatedByString:#"app2://"] lastObject];
NSString* perString=[dataString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSKeyedUnarchiver* unArchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:[perString dataUsingEncoding:NSASCIIStringEncoding]];
TempItem* temp=[unArchiver decodeObjectForKey:#"TempData"];
[unArchiver finishDecoding];
//...//
}
Is there more to encoding/decoding custom classes that I am missing? I do implement NSCoding in my class the problem I think is in
[perstring dataUsingEncoding:NSASCIIStringEncoding]
as it appears to always be null?
Thanks!
I checked the output after the encoding and it is as such
bplist00Ô,-T$topX$objectsX$versionY$archiverÑXTempData©
'U$nullÖ
XitemsizeXquantityUpriceV$classYconvertedTunitQ1#?ð
and after adding percent escapes
bplist00%C3%94%01%02%03%04%05%08,-T$topX$objectsX$versionY$archiver%C3%91%06%07XTempData%C2%80%01%C2%A9%09%0A%17%18%19%1A%1B%1F'U$null%C3%96%0B%0C%0D%0E%0F%10%11%12%13%14%15%16XitemsizeXquantityUpriceV$classYconvertedTunit%C2%80%03%C2%80%05%C2%80%04%C2%80%08%C2%80%06%C2%80%02Q1%23?%C3%B0%00%00%00%00%00%00%23?%C3%B0%00%00%00%00%00%00%10%01%C3%92%1C%0E%1D%1EZNS.objects%C2%A0%C2%80%07%C3%92%20!%22&X$classesZ$classname%C2%A3%23$%25%5ENSMutableArrayWNSArrayXNSObject%5ENSMutableArray%C3%92%20!(+%C2%A2)*XTempItemXNSObjectXTempItem%12%00%01%C2%86%C2%A0_%10%0FNSKeyedArchiver%00%08%00%11%00%16%00%1F%00(%002%005%00%3E%00#%00J%00P%00%5D%00f%00o%00u%00%7C%00%C2%86%00%C2%8B%00%C2%8D%00%C2%8F%00%C2%91%00%C2%93%00%C2%95%00%C2%97%00%C2%99%00%C2%A2%00%C2%AB%00%C2%AD%00%C2%B2%00%C2%BD%00%C2%BE%00%C3%80%00%C3%85%00%C3%8E%00%C3%99%00%C3%9D%00%C3%AC%00%C3%B4%00%C3%BD%01%0C%01%11%01%14%01%1D%01&%01/%014%00%00%00%00%00%00%02%01%00%00%00%00%00%00%00.%00%00%00%00%00%00%00%00%00%00%00%00%00%00%01F
I added NSLogs on the decode portion and it is the same. I am baffled...
After fixing the misplacement of the [unArchiver finishdecoding]; I now get the error
*** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL

Cast JSON object (NSCFDictionary) to string and parse it

I'm working with facebook connect and trying to handle the JSON object that i'm receiving.
I invoked the requstWithGraphPath method and need to get back a JSON object,
tried to parse it and getting an error:
SBJSON *parser = [[SBJSON new] autorelease];
NSData *data = [[NSData alloc] initWithData:result];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; -> in this line - "[__NSCFDictionary length]: unrecognized selector sent to instance"
NSArray *events = [parser objectWithString:jsonString];
What's the problem?
Can I get the string in an other way or parse the object differently?
Thanks.
If you are working with the delegate callback
- (void)request:(FBRequest *)request didLoad:(id)result;
the parsing work has been done for you. Traverse the NSDictionary or NSArray to find the data you are looking for. If you are working with the delegate callback
- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data;
you should initialize an NSString with the data, and use the category method that SBJSON adds to NSString for creating an id. That is assuming the data is data that constructs a string.
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
id result = [jsonString JSONValue];
Are you sure the error happens on that line, or does it happen on the line above?
If result is an NSDictionary (or CFDictionary, same thing), then it is already parsed and you do not need to do that yourself — and it could cause that error message too, on the line above.
The line:
data = [[NSData alloc] initWithData:result];
is almost certainly not what you want to do, as it is equivalent to
data = [result copy];
assuming that result is an NSData object (or NSMutableData), which I'm guessing it isn't.

Extracting array from NSMutableData in http response

using iphone sdk 4.0. The callback for an http request gives data as an NSData object
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the data received to our data
[theData appendData:data];
}
In my php script on the server i am returning an array as follows
var_dump($array).
How do i get my array back from the NSMutableData object 'theData' obove on my iphone.
Thanks
You have a string describing your array (or maybe several arrays?) stored as a sequence of bytes in your NSMutableData object. In order to turn it back into an array you're going to need to parse the var_dump output, which is likely to be arduous.
If you can find a library (or roll your own code) to return your data in Apple plist format, your task will be much easier: you can use
[NSPropertyListSerialization propertyListFromData:mutabilityOption:format:errorDescription:]
which takes an NSData (or NSMutableData) pointer as its first argument. Try http://code.google.com/p/cfpropertylist/ for a starting point.
From the example code at the cfpropertylist page:
$plist = new CFPropertyList();
$td = new CFTypeDetector();
$guessedStructure = $td->toCFType( $array );
$plist->add( $guessedStructure );
// and then return the plist content with
$plist->toXML()
and in your iOS code:
NSString *errorString = nil;
NSArray *array = [[NSPropertyListSerialization
propertyListFromData:theData
mutabilityOption:NSPropertyListImmutable
format:nil
errorDescription:&errorString] retain];
I would likely use YAJL on iOS, and $var = json_encode($array); in the PHP. Then in the iOS, I would parse that content from the NSData input like:
YAJLParser *parser = [[YAJLParser alloc] initWithParserOptions:YAJLParserOptionsAllowComments | YAJLParserOptionsCheckUTF8];
parser.delegate = [[[MyArrayParserDelegate alloc] init] autorelease];
[parser parse:data];
NSArray *thePhpArrayReceived = parser.delegate.resultantArray;
Please check out how to structure the delegate, and get YAJL here : Get YAJL + Readme
PHP outputs text so you will have to read that NSData as NSString and then parse out the array data according to the format specified by var_dump. As a starting point, the following code snippet should print out the array (as text) to your console:
NSString * dump = [[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding];
NSLog(#"%#", dump);
[dump release];
As Seamus Campbell points out, there are better ways of doing this. Another option would be to output XML from your PHP script, and then use Cocoa's XML parsing methods to retreive the array.