Sending byte data to web service in cocos2d iphone - iphone

I want to send my Byte data using some existed web service . Now i don't want to explore on Web service more but i just want my following Byte data to some already existed web service.
for Example , following is my Byte Data .
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, (Byte*)myData, len);
How can i do this !? i want to use Existed Web Service only,your help would be appreciated a lot .
EDITED
i have my NSData in json format too . as below code
const unsigned char *bytes = [myData bytes]; // no need to copy the data
NSUInteger length = [myData length];
NSMutableArray *byteArray = [NSMutableArray array];
for (NSUInteger i = 0; i < length; i++)
{
[byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]];
}
NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
byteArray, #"vedio",
nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJson options:0 error:NULL];

i simply send my NSdata or say ByteData like this :
NSMutableDictionary *dictParam = [NSMutableDictionary dictionary];
[dictParam setValue:mydata forKey:#"pattern"];
NSString *Web_str_pattern = #"my webservice link";
JSONParser *parser = [[JSONParser alloc]initWith_withURL:Web_str_pattern withParam:dictParam withData:nil withType:kPostURL withSelector:#selector(getData:) withObject:self];
Here , i am using JSONParser for web service.

Related

UIImage Not being Set from NSData

The goal is to pull a image stored as a varbinary in a sql server through a web service that sends a sqlbinary as a JSON to an iphone. I'm having trouble setting the UIImage from the base64binary sent from the JSON. I'm able to convert the binary to NSData but the image is not being set through the data.
for (int i = 0; i < array.count; i++) {
NSDictionary *mealInfo = [array objectAtIndex:i];
Meal *meal =[[Meal alloc]initWithRestaurant:[mealInfo objectForKey:#"restaurantname"]
mealName:[mealInfo objectForKey:#"itemname"]
description:[mealInfo objectForKey:#"itemdescription"]
Time:[mealInfo objectForKey:#"mealTime"]
price:[mealInfo objectForKey:#"itemprice"]];
//NSString *str = #"data:image/jpg;base64,";
//str = [str stringByAppendingString:[mealInfo objectForKey:#"itemImage"]];
//NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
NSString *str = [mealInfo objectForKey:#"itemImage"];
NSLog(#"%#", str);
NSData *d = [[NSData alloc]initWithData:[NSData dataFromBase64String:str]];
UIImage *image = [UIImage imageWithData:d];
[meal setMealImage:image];
[meals addObject:meal];
}
NSLog(#"%#",[[meals objectAtIndex:0]mealPrice]);
NSLog(#"This is how many meals %d", meals.count);
Assuming the string containing the base 64 encoded is good, your code looks OK. I would look at the dataFromBase64String method to see if that is causing the problem. Here is a version I use based on some else's work:
-(NSData *)dataFromBase64EncodedString:(NSString *)string{
if (string.length > 0) {
//the iPhone has base 64 decoding built in but not obviously. The trick is to
//create a data url that's base 64 encoded and ask an NSData to load it.
NSString *data64URLString = [NSString stringWithFormat:#"data:;base64,%#", string];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]];
return data;
}
return nil;
}
You could add a NSData category with this method to make its use very convenient.

Adding more variables to NSData for turn-based gaming data encoding

I am making a turn-based game where I have stored an integer variable 'points' into NSData, which is then stored by gamecenter. So far I am doing this as follows:
NSString *newString=[[NSString alloc] initWithFormat: #"%i", points];
NSData *data = [newString dataUsingEncoding:NSUTF8StringEncoding];
I need to store more variables into NSData *data. How can i do this?
I am now aware that you can store 2 integers in the string *newString by:
NSString *newString=[[NSString alloc] initWithFormat: #"%i, %i", points, otherInteger];
However I don't know how I would decode this as the string would be stored as one integer value following on from the last. It might not be the best implementation anyway so any suggestions would be appreciated.
You could do something like this:
// for encoding
int32_t points = ...;
int32_t otherInteger = ...;
NSMutableData *data = [NSMutableData data];
[data appendBytes:&points length:sizeof(int32_t)];
[data appendBytes:&otherInteger length:sizeof(int32_t)];
.
.
.
// for decoding
NSData *data = ...;
int32_t points;
int32_t otherInteger;
int index = 0;
NSRange range;
range = NSMakeRange(index, sizeof(int32_t));
[data getBytes:&points range:range];
index += sizeof(int32_t);
range = NSMakeRange(index, sizeof(int32_t));
[data getBytes:&otherInteger range:range];
index += sizeof(int32_t);
.
.
.

iOS zip with gzipDeflate

I'm using the NSData+compression.h and the Base64Transcoder.h elements to be able to zip and unzip content.
Basically to unzip the server responses.
The unzip method works perfectly
+ (NSString *) unzip: (NSString*) stringValue{
Byte inputData[[stringValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[[stringValue dataUsingEncoding:NSUTF8StringEncoding] getBytes:inputData];
size_t inputDataSize = (size_t)[stringValue length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);
Byte outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64DecodeData(inputData, inputDataSize, outputData, &outputDataSize);
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];
//And now we gunzip:
NSData* result = [theData gzipInflate];//make bigger==gunzip
NSString *temp = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
return temp;
}
But when I try to zip a content, using the simetric way, the gzipDeflate fails, and return an empty or nil value.
This is my zip code
+ (NSData *) zip:(NSData *) theSourceData {
// And now we zip:
NSData *result = [theSourceData gzipDeflate];
Byte inputData[[result length]];
[result getBytes:inputData];
size_t inputDataSize = (size_t)[result length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);
char outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64EncodeData(inputData, inputDataSize, outputData, &outputDataSize, NO);
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];
return theData;
}
Any suggestions?
Thanks
The problem was on the Base64 encoder.
+ (NSString *) zip:(NSData *) theSourceData {
// And now we zip:
NSData *result = [theSourceData gzipDeflate];
NSString *source = [NSString base64StringFromData:result length:[result length]];
return source;
}
We've integrated the base64StringFromData:length: method to solve it.
Thanks,
Ivan

NSData to NString conversion problem

I'm getting an HTML file as NSData and need to extract some parts of it. For that I need to convert it to NSString with UTF8 encoding. The thing is that this conversion fails, probably because the NSData contains bytes that are invalid for UTF8. I have tried to get the byte array of the data and go over it, but each time I come across non ASCII character (hebrew letters for example) I get jibrish.
Help will be appreciated.
UPDATE:
To Gordon - the NSData generated like that:
NSData *theData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
When I say that the conversion fails I mean that
[[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding]
returns nil
To Ed - Here is my code (I got the Byte array from NSData, found what I need, and constructed another Byte array from that - turned it to NSData and then attempted to convert it to NSString... sounds kinda complicated...)
-(NSString *)UTF8StringFromData:(NSData *)theData{
Byte *arr = [theData bytes];
NSUInteger begin1 = [self findIndexOf:#"<li>" bArr:arr size:[theData length]]+4;
NSUInteger end1 = [self findIndexOf:#"</li></ol>" bArr:arr size:[theData length]];
Byte *arr1 = (Byte *)malloc(sizeof(Byte)*((end1-begin1+1)));
NSLog(#"%d %d",begin1, end1);
int j = 0;
for (int i = begin1; i < end1; i++){
arr1[j] = arr[i];
j++;
}
arr1[j]='\0';
NSData *temp = [NSData dataWithBytes:arr1 length:j];
return [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
}
I know this is an old topic but it came up when I was looking for the solution today. I've solved it now so I'm just posting it for others who might run into this page looking for a solution.
Here's what I do in an asynchronous request:
I first store the text encoding name in connection:didReceiveResponse using
encodingName = [[NSString alloc] initWithString:[response textEncodingName]];
Then later in my connectionDidFinishLoading method I used
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef) encodingName));
NSString *payloadAsString = [[NSString alloc] initWithData:receivedData encoding:encoding];
To Gordon - the NSData generated like that:
NSData *theData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
When I say that the conversion fails I mean that
[[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding]
returns nil
To Ed - Here is my code (I got the Byte array from NSData, found what I need, and constructed another Byte array from that - turned it to NSData and then attempted to convert it to NSString... sounds kinda complicated...)
-(NSString *)UTF8StringFromData:(NSData *)theData{
Byte *arr = [theData bytes];
NSUInteger begin1 = [self findIndexOf:#"<li>" bArr:arr size:[theData length]]+4;
NSUInteger end1 = [self findIndexOf:#"</li></ol>" bArr:arr size:[theData length]];
Byte *arr1 = (Byte *)malloc(sizeof(Byte)*((end1-begin1+1)));
NSLog(#"%d %d",begin1, end1);
int j = 0;
for (int i = begin1; i < end1; i++){
arr1[j] = arr[i];
j++;
}
arr1[j]='\0';
NSData *temp = [NSData dataWithBytes:arr1 length:j];
return [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
}
have you checked the charset= in the HTTP headers and/or the document itself? The most likely reason for the conversion to fail is because the bytes don't represent a valid UTF-8 string.
I'm not sure if you're aware, you don't really need to copy the array to another array before putting it into the new NSData object.
-(NSString *)UTF8StringFromData:(NSData *)theData {
Byte *arr = [theData bytes];
NSUInteger begin1 = [self findIndexOf:#"<li>" bArr:arr size:[theData length]]+4;
NSUInteger end1 = [self findIndexOf:#"</li></ol>" bArr:arr size:[theData length]];
Byte *arr1 = arr + begin1;
NSData *temp = [NSData dataWithBytes:arr1 length:end1 - begin1];
return [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
}
As for your particular problem, I would try looking through the data manually using the debugger. Put a breakpoint after you have your array (arr1). When you hit it, open up the GDB console and try this:
print (char *)arr1
With your code, it should print out the string you're trying to get. (With the code I gave above, it won't stop after the . It'll just keep going).
If the result is not what you expect, then there's something wrong with the data, or perhaps with your begin1 and end1 boundaries.

Trying to parse twitter trends

Im trying to parse twitter trends but i keep getting a parser error at "as_of". anyone know why this is happening?
EDIT:
Here is the code im using
NSMutableArray *tweets;
tweets = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://search.twitter.com/trends/current.json"];
trendsArray = [[NSMutableArray alloc] initWithArray:[CCJSONParser objectFromJSON:[NSString stringWithContentsOfURL:url encoding:4 error:nil]]];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i = 0; i < [trendsArray count]; i++) {
dict = [[NSMutableDictionary alloc] init];
//[post setObject: [[currentArray objectAtIndex:i] objectForKey:#"query"]];
[dict setObject:[trendsArray objectAtIndex:i] forKey:#"trends"];
//[dict setObject:[trendsArray objectAtIndex:i] forKey:#"query"];
//[post setObject:[trendsArray objectAtIndex:i] forKey:#"as_of"];
[tweets addObject:dict];
//post = nil;
}
I'm not exactly sure what your problem could be but I've had a play with the twitter api and CCJSON and have got some sample code that seems to work. If you cut and paste it into the applicationDidFinishLaunching method of a new project and include the CCJSON files it will just work (hopefully).
This code will take the trends json from twitter, output the as_of value and create an array of trends.
// Make an array to hold our trends
NSMutableArray *trends = [[NSMutableArray alloc] initWithCapacity:10];
// Get the response from the server and parse the json
NSURL *url = [NSURL URLWithString:#"http://search.twitter.com/trends/current.json"];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:4 error:nil];
NSDictionary *trendsObject = (NSDictionary *)[CCJSONParser objectFromJSON:responseString];
// Output the as_of value
NSLog(#"%#", [trendsObject objectForKey:#"as_of"]);
// We also have a list of trends (by date it seems, looking at the json)
NSDictionary *trendsList = [trendsObject objectForKey:#"trends"];
// For each date in this list
for (id key in trendsList) {
// Get the trends on this date
NSDictionary *trendsForDate = [trendsList objectForKey:key];
// For each trend in this date, add it to the trends array
for (NSDictionary *trendObject in trendsForDate) {
NSString *name = [trendObject objectForKey:#"name"];
NSString *query = [trendObject objectForKey:#"query"];
[trends addObject:[NSArray arrayWithObjects:name, query, nil]];
}
}
// At the point, we have an array called 'trends' which contains all the trends and their queries.
// Lets see it . . .
for (NSArray *array in trends)
NSLog(#"name: '%#' query: '%#'", [array objectAtIndex:0], [array objectAtIndex:1]);
Hope this is useful, comment if you have any questions,
Sam
PS I used this site to visualise the JSON response - it made it much easier to see what is going on - I just cut and paste the JSON from twitter into it :)