Base 64 encoding random behaviour UIImage - iphone

I am sending an image to the server by converting the NSData object into an NSString object using Base64 scheme by using....
NSData *imgData=UIImagePNGRepresentation([objCP userImage]);
NSString *encodedString=[Base64Coder encodeData:imgData];
I am observing a random behavior....sometimes I get "==" in the encoded string at the end of the string and image does not uploaded.There may be some other characters also in between the string.If I do not get these characters at the end...image gets uploaded.
To overcome this...I also used this method to convert these characters into valid(assumed to be accepted)::
-(NSString *)urlEncodedVersion:(NSString *)strString
{
NSMutableString *strTemp = [[NSMutableString alloc] initWithFormat:#"%#",strString] ;
NSArray *escapeChars = [NSArray arrayWithObjects:#";",#"?",#":",#"#", #"&",#"=",#"+",#"$",#",", #"[",#"]",#"#",#"!",#"’",#"(", #")",#"*",#" ",nil];
NSArray *replaceChars = [NSArray arrayWithObjects: #"%3B",#"%3F",#"%3A",
#"%40",#"%26",#"%3D", #"%2B",#"%24",#"%2C",#"%5B",#"%5D", #"%23",#"%21",#"%27", #"%28",#"%29",#"%2A",#"%20",nil];
//NSMutableString *tempStr = [[self mutableCopy] autorelease];
for(int i = 0; i < [escapeChars count]; i++)
{
[strTemp replaceOccurrencesOfString:[escapeChars objectAtIndex:i] withString:[replaceChars objectAtIndex:i] options:NSLiteralSearch range:NSMakeRange(0,[strTemp length])];
}
return strTemp;
}
but it is also not serving.
This is my whole post body::
-(void)uploadProfileInfo:(CreateProfile *)objCP
{
NSData *imgData=UIImagePNGRepresentation([objCP userImage]);
NSString *encodedString=[Base64Coder encodeData:imgData];
NSString *refinedString=[self urlEncodedVersion:encodedString];
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<soapenv:Envelope \n"
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" \n"
"xmlns:tem=\"http://tempuri.org/\" \n"
"xmlns:wcf=\"http://schemas.datacontract.org/2004/07/NextToMe_BusinessEntity\"> \n"
"<soapenv:Header/>\n"
"<soapenv:Body>\n"
"<tem:CreateProfile>\n"
"<tem:objUser>\n"
"<wcf:Email>%#</wcf:Email>\n"
"<wcf:Mode>%#</wcf:Mode> \n"
"<wcf:Name>%#</wcf:Name>\n"
"<wcf:ProfileImage>%#</wcf:ProfileImage>\n"
"<wcf:RequestDateTime>%#</wcf:RequestDateTime>\n"
"<wcf:Status>%#</wcf:Status>\n"
"<wcf:StatusSpecified>%#</wcf:StatusSpecified>\n"
"<wcf:UDID>%#</wcf:UDID>\n"
"</tem:objUser>\n"
"</tem:CreateProfile>\n"
"</soapenv:Body>\n"
"</soapenv:Envelope>\n",[objCP email],[objCP mode],[objCP name],encodedString,#"",[objCP status],[objCP statusSpecified],[objCP UDID]];
NSURL *url = [NSURL URLWithString:kBaseURL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/XXXX/CreateProfile" forHTTPHeaderField:#"Soapaction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"The Connection is NULL");
}
}

The = characters you see at the end are padding. This is according to RFC4648 3.2. Padding of Encoded Data. The other end should be able to digest that. Apparently that is not happening. You should compare the behavior with a third party library to check whether the encoding or decoding is wrong. If you can make it work removing the padding, then good for you, but that's a fault in the decoding library.

Related

Add new place to Google Places

I am new to IOS. I have to add new places to Google Places. I have referred this link https://developers.google.com/places/documentation/actions to add a place on button click, but I'm confused about passing parameters for this.
My coding lines are like this to fetch:
NSString *lat =#"-33.8669710";
NSString *longt =#"151.1957362";
gKey = #"my api key";
NSString *placeString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=%#HTTP/1.1Host:maps.googleapis.com {\"location\":{\"lat\":%#,\"lng\":%#},\"accuracy\": 50,\"name\":\"Gimmy Pet Store!\",\"types\":[\"pet_store\"],\"language\":\"en-AU\"}",gKey,lat,longt];
placeString = [placeString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Main Place Url: %#",placeString);
NSURL *placeURL = [NSURL URLWithString:placeString];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:placeURL];
[request setHTTPMethod:#"POST"];
NSURLConnection *placesConn =[[NSURLConnection alloc] initWithRequest:request delegate:self];
I have made following changes to my code & finally it is executed successfully...
//for setting Parameters to post the url.just change tag values to below line...
NSString *str1 = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><PlaceAddRequest><location><lat>your latitude</lat><lng>your longitude</lng></location><accuracy>50</accuracy><name>place name</name><type>supported type</type><language>en-US</language></PlaceAddRequest>"];
NSLog(#"str1=====%#",str1);
NSString *str2 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *requestdata = [NSData dataWithBytes:[str2 UTF8String] length:[str2 length]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestdata length]];
//requesting main url to add new place to google places
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/add/xml?sensor=false&key=your api key"]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:[str1 UTF8String] length:[str1 length]]];
//NSURLConnection *placesConn =[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *returndata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnstr = [[[NSString alloc] initWithData:returndata encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"returnstr: %#",returnstr);
& then i have decoded return response which i get i status as OK......:)
Any one can use above code...if any help require you can surely ask....:)

Call WSDL soap method in iPhone

i am working on an iPhone project in which i have a wsdl which is having description of methods and these methods contains an xml. I need to call these methods which are there in wsdl to get the xml using soap and parse it. I have read so many links and tutorials but was not able to to call the method in the wsdl. Please if u can provide me some links or suggestions.
you can use http://sudzc.com/ ,it gives you ready WSDL
This is a .NET web site solution that uses XSLT to transform SOAP-based web service definition WSDL files into complete code packages. The code that is generated is easy to read and update.
While SudzC supports multiple platforms, it's focus is on code generation for Objective-C libraries for iPhone development.
reference http://code.google.com/p/sudzc/
Please try this code. It worked for me.
[Note: GetDictionary is my method name which is displayed in Web service.and in url please write the url displayed in web service at below portion. It should be matched with url you have written in coding otherwise you will not get output(better copy it from web service)]
-(IBAction)loadData
{
NSString *soapMessage = [NSString stringWithFormat:
#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<SOAP-ENV:Body>\n"
"<GetDictionary></GetDictionary>\n"
"</SOAP-ENV:Body>\n"
"</SOAP-ENV:Envelope>"];
NSURL *url = [NSURL URLWithString:#"http://c70.narolainfotech.local/WCFTest/RestServiceImpl.svc/basic"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"urn:RestServiceImpl/GetDictionary" forHTTPHeaderField:#"soapAction"];
// [theRequest addValue: #"urn:RestServiceImpl/getDataBY_ID" forHTTPHeaderField:#"soapAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection)
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
}
In connectionDidFinishLoading write following code:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *strData = [[NSString alloc]initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"result : %#",strData);
NSString *result=nil;
NSString *str;
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
theXML = [theXML stringByReplacingOccurrencesOfString:#"<" withString:#"<"];
theXML = [theXML stringByReplacingOccurrencesOfString:#">" withString:#">"];
theXML = [theXML stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
//NSLog(#"XML from Web-Service ======= \n\n %#",theXML);
NSArray *array=[theXML componentsSeparatedByString:#"<GetDictionaryResult>"];
for(int i=1;i<[array count];i++)
{
str=[array objectAtIndex:i];
NSRange ranfrom=[str rangeOfString:#"</GetDictionaryResult>"];
result =[str substringToIndex:ranfrom.location];
}
NSLog(#"result ::: %#",result);
}
Just Hope that it'll work for you. :)

converting image to base64 and uploading in JSON format to server

I have a problem. I need to convert base64 string to JSON string and pass it to server.
for example I have a base64 string /9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/Z
i need to convert it to JSON format. I do the following:
+(NSData *)prepareForUploading:(NSString *)base64Str
{
NSDictionary *dict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:base64str, nil] forKeys:[NSArray arrayWithObjects:#"picture", nil]];
NSData *preparedData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return preparedData;
};
here how I'm making NSURLRequest
-(NSString *)uploadPict:(NSString *)pict
{
NSLog(#"Server: upload: called");
NSData *prepPictData=[[self class] prepareForUploading:pict];
NSString *preparedBase64StrInJSON=[[NSString alloc] initWithData:prepPictData encoding:NSUTF8StringEncoding];
//here I'm adding access token to request
NSString *post = [NSString stringWithFormat:#"accessToken=%#&object=%#", self.key, preparedBase64StrInJSON];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upload.aspx", serverAPIPath]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"postLength" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//....
}
But I get "Invalid length for a Base-64 char array" from server. What's wrong?
If I paste my token and JSON to http://hurl.it/ and make request using it - everything goes normally.
I think the problem is / symbols in base64 string and as a result / symbols in JSON.
Maybe it is something with [postData length]: if I erase \/ characters from JSON string:
9j4AAQSkZJRgABAQAAAQABAAD4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQHZ request will perform normally but this base64 encoded string is not the same.
Please, help me to solve this problem
jString is your base64 string, first use following line
[self encodeString:jString];
and then call use following.
NSString *URL = [NSString stringWithFormat:#"forms.asmx/CreateUpdate?"];
URL=[NSString stringWithFormat:#"%#%#", USERS_API_ROOT_URL, URL];
NSString *post = [NSString stringWithFormat:#"apiKey=A0B1I2L3A4L5-A1D3-4F30-5AB2-C8DEE266&strPost=%#",jString];
unsigned long long postLength = [post length];
NSString *contentLength = [NSString stringWithFormat:#"%llu",postLength];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(NSString *)encodeString:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL,CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return newString;
}
Hope it will work.

Response encryption problem

I get the response as follow:
TIMESTAMP=2011%2d09%2d22T10%3a20%3a24Z&CORRELATIONID=fa0181684fd81&ACK=Success
&VERSION=65%2e0&BUILD=2133933&AMT=0%2e12&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M
&TRANSACTIONID=6PT23270XK626941N" in this encrypted format
How can I get original text string? This is my code for Parsing the URL :
NSString *parameterString = [[NSString stringWithFormat:#"USER=mercha_1316582882_biz_api1.ifuturz.com"
"&PWD=1316582974"
"&SIGNATURE=Az-qrCDOk-pVcMVvJLOJY7DrGESBAgSH4RGOILESJSsYaBlWVZ3mNfJB"
"&METHOD=DoDirectPayment"
"&CREDITCARDTYPE=Visa"
"&ACCT=%#"
"&EXPDATE=092016 "
"&CVV2=111"
"&AMT=%#"
"&FIRSTNAME=%#"
"&LASTNAME=%#"
"&STREET=%#"
"&CITY=%#"
"&STATE=%#"
"&ZIP=%#"
"&COUNTRYCODE=IN"
"&CURRENCYCODE=USD"
"&PAYMENTACTION=Sale"
"&VERSION=65.0",
txtCreditCardNo.text,
strAmount,
txtName.text,
txtName.text,
txtAddress.text,
txtCity.text,
txtState.text,
txtZipCode.text
] retain];
NSLog(#"Soap : %#",parameterString);
NSURL *url = [NSURL URLWithString:#"https://api-3t.sandbox.paypal.com/nvp"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [parameterString length]];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [parameterString dataUsingEncoding:NSUTF8StringEncoding]];
NSError *err;
NSURLResponse *resp;
NSData *response = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&resp error:&err];
if (resp != nil) {
NSString *stringResponse = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"---------------------- %#",stringResponse);
SBJSON *jsonParser = [SBJSON new];
NSMutableDictionary *json = [[NSMutableDictionary alloc] init];
json = [jsonParser objectWithString:stringResponse error:NULL];
NSLog(#"\n \n JSN Dic : %#",[json description]);
} else if (err != nil) {
NSLog(#"\n \n Nill");
}
It is not encrypted, it is URL Encoded, that is troublesome characters are replaced with their hex values. Ex: '%2d' is '-'.
NSString *stringToDecode = #"TIMESTAMP=2011%2d09%2d22T10%3a20%3a24Z&CORRELATIONID=fa0181684fd81&ACK=Success&VERSION=65%2e0&BUILD=2133933&AMT=0%2e12&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=6PT23270XK626941N";
NSString *decodedString = [stringToDecode stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"decodedString: %#", decodedString);
NSLog output:
decodedString: TIMESTAMP=2011-09-22T10:20:24Z&CORRELATIONID=fa0181684fd81&ACK=Success&VERSION=65.0&BUILD=2133933&AMT=0.12&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=6PT23270XK626941N

post xmldata through webservice iphone problem

This is my xml
NSString *Message = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<query>\n"
"<IdCategory>1088</IdCategory>\n"
"</query>\n"];
NSURL *url = [NSURL URLWithString:#"http://bvd.vndsupport.com/_ws/api/categories/index.asp"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [Message length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [Message dataUsingEncoding:NSUTF8StringEncoding]];
NSString *returnString = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
I have simply pass this category id and get the result but returnString always display all category details. I didn't get an exact result. Is this the correct way of passing xml data to webservice?
go and search for 'wsdl2objc' it does it all for you if you wanted to do soap requests.
This code will work perfectly. the problem is webservice page