Trouble in sending data to server in ios - iphone

I am creating ios and android application which include chatting mechanisum.
I got problem in ios application when I am sending message to server. Sometime message send by ios device get repeated entry in server database. It happen rearly.
I am using ASIFormDataRequest class for communicating with server in ios.
My android app also using same API for communicating with server. Android app works properly
Code for sending message in ios is as follow.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urlString];
[request setRequestMethod:#"POST"];
for (NSString* key in dictionaryWithValue) {
[request setPostValue:[dictionaryWithValue objectForKey:key] forKey:key];
}
[request setTimeOutSeconds:60];
[request setDelegate:self];
[request setShouldContinueWhenAppEntersBackground:YES];
request.shouldAttemptPersistentConnection = NO;
[request startSynchronous];
Here dictionaryWithValue is NSDictonary which contain data in key value pair.
Is there in anything getting wrong in code?
Also in ios application, image is not uploading to server. it get connection time out.
For uploading image i have used following code
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setTimeOutSeconds:120];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setUploadProgressDelegate:self];
[request setShouldAttemptPersistentConnection:YES];
[request setData:[parametersPOST objectAtIndex:2] withFileName:#"UserAvatarFile.png" andContentType:#"image/png" forKey:KEYAvatar];
[request startSynchronous];
NSString *fileName = [parametersPOST objectAtIndex:1];
[request setData:[parametersPOST objectAtIndex:2] withFileName:fileName andContentType:#"image/jpg" forKey:KEYAvatar];
[request setPostValue:[parametersPOST objectAtIndex:2] forKey:#"avatar"];
[request addPostValue:[parametersPOST objectAtIndex:2] forKey:#"avatar"];
[request setPostValue:[parametersPOST objectAtIndex:0] forKey:#"userid"];
[request setPostValue:fileName forKey:#"name"];
[request setPostValue:[parametersPOST objectAtIndex:3] forKey:#"token"];
[request startSynchronous];
Here parametersPOST is NSArray which contain data which i have to send to server.

+(NSDictionary *)getParsedDictonaryforUrlString:(NSString *)urlString withData:(NSData *)postData
{
NSString *newURL = urlString;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:newURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: postData];
// get response
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
if (responseData == nil)
{
// Check for problems
if (responseData != nil)
{
}
}
else
{
// Data was received.. continue processing
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >=200 && [urlResponse statusCode] <300)
{
NSLog(#"Response ==> %#", result);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:result error:parseError];
return xmlDictionary;
}
}
return nil;
}
This method may help to you

Related

Sending Mp4 Video to PHP server via ASIFormDataRequest

Here I am sending the file path or file with some parameters. But the server didn't get the video. So any problem in that code? Or anything you want to add something. Then please tell me. Any delegate method you want to tell me where I get error or setting in response .
NSString *path = [[NSBundle mainBundle] pathForResource:#"hangover" ofType:#"mp4"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://156.75.28.172:52/aircas/RestServices/fileUpload"]];
[request setPostValue:filename forKey:#"name"];
[request setPostValue:#"GUnit" forKey:#"title"];
[request setPostValue:#"133" forKey:#"user_id"];
[request setPostValue:#"8953d0e1c97ef83c9f0aff47" forKey:#"token"];
[request setPostValue:#"video song" forKey:#"desc"];
[request setPostValue:#"34" forKey:#"video_id"];
[request setPostValue:#"0" forKey:#"is_private"];
[request setFile:path forKey:#"video"];
[request setTimeOutSeconds:500];
[request setRequestMethod:#"POST"];
[request startSynchronous];
Try this...
NSString *path = [[NSBundle mainBundle] pathForResource:#"hangover" ofType:#"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:path];
NSData *movieData = [NSData dataWithContentsOfURL:fileURL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://156.75.28.172:52/aircas/RestServices/fileUpload"]];
[request setPostValue:filename forKey:#"name"];
[request setPostValue:#"GUnit" forKey:#"title"];
[request setPostValue:#"133" forKey:#"user_id"];
[request setPostValue:#"8953d0e1c97ef83c9f0aff47" forKey:#"token"];
[request setPostValue:#"video song" forKey:#"desc"];
[request setPostValue:#"34" forKey:#"video_id"];
[request setPostValue:#"0" forKey:#"is_private"];
[self.request setData:movieData withFileName:#"hangover.mp4" andContentType:#"multipart/form-data" forKey:#"video"];
[request setTimeOutSeconds:500];
[request setRequestMethod:#"POST"];
[request startSynchronous];
Hope it helps.
Add following code in your code and than you can write 2 delegate methods and can handle response.
[request setDelegate:self];
[request setDidFailSelector:#selector(uploadFailed:)];
[request setDidFinishSelector:#selector(uploadFinished:)];
- (void) uploadFailed:(ASIHTTPRequest *)request
{
//Upload succeeded;
}
- (void) uploadFinished:(ASIHTTPRequest *)request
{
//Upload failed;
NSError *error = [request error];
NSLog(#"Error Description-->%#",[error localizedDescription]);
}
To have indepth view for ASIHttpRequest please see documentation. Its very well documented.

How to authenticate id password in Gdata video upload to you tube

To upload vedio on you tube i am using Gdata sample code.
Its working fine as it is. But in my application I need to authenticate username and password of user before user try to upload video.
Can I do it with Gdata service ?
Thanks for any help.
Below is method for client login in Youtube:
- (BOOL)login:(NSString *)strusername password:(NSString *)strpassword
{
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"https://www.google.com/accounts/ClientLogin"]];
NSString *params = [[NSString alloc] initWithFormat:#"Email=%#&Passwd=%#&service=youtube&source=&continue=http://www.google.com/",username,password];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[params release];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
NSHTTPURLResponse *response;
NSError *error;
[request setTimeoutInterval:120];
NSData *replyData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *replyString = [[[NSString alloc] initWithData:replyData encoding:NSUTF8StringEncoding] autorelease];
if([replyString rangeOfString:#"Auth="].location!=NSNotFound)
{
NSString *authToken=[[replyString componentsSeparatedByString:#"Auth="] objectAtIndex:1];
NSLog(#"Auth : %#",authToken);
return YES;
}
else
{
return NO;
}
}

Problem with Response asihtttprequest

NSURL *url = [NSURL URLWithString:#"someurl"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:year1 forKey:#"year"];
[request setPostValue:appy_level forKey:#"appy_level"];
[request setPostValue:reasons forKey:#"reasons"];
[request setPostValue:country forKey:#"country"];
[request setPostValue:city forKey:#"city"];
[request setPostValue:sex forKey:#"sex"];
[request setRequestMethod:#"POST"];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
NSLog(#"response -%#",[request responseString]);
[self dismissModalViewControllerAnimated:YES];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
NSLog(#"%#",response);
}
any idea why this code return (null) i mean response is null? and this requestFinised: method isnt working even i write[requestsetDidFinishSelector:#selector(requestFinished)];
method too.I am confuesed right now.
The first NSLog won't work because you start your request as asynchronous.
You chould try putting NSLog(#"finished"); in -requestFinished: to check if page is loading or not. It can be an error in your server file (e.g. php fatal error).
Have you tried this:
NSString *response = [[NSString alloc] initWithData:[request data] encoding:NSUTF8StringEncoding];
NSLog(#"%#", response);

How to login in youtube with loginClient (iOS app)

I develop Youtube app for iphone. One of my tasks - login on Youtube. I need objective-c sample for LoginClient Request and taking marker from it.
Like this model of loginClient.
Very very Thank's!
- (BOOL)login:(NSString *)username password:(NSString *)password{
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"https://www.google.com/accounts/ClientLogin"]];
NSString *params = [[NSString alloc] initWithFormat:#"Email=%#&Passwd=%#&service=youtube&source=&continue=http://www.google.com/",username,password];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
NSHTTPURLResponse *response;
NSError *error;
[request setTimeoutInterval:120];
NSData *replyData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *replyString = [[NSString alloc] initWithData:replyData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",replyString);
if([replyString rangeOfString:#"Auth="].location!=NSNotFound){
authToken=[[replyString componentsSeparatedByString:#"Auth="] objectAtIndex:1];
return YES;
}else{
return NO;
}
}
I think this is what you need. This get the authentication token using ClientLogin scheme.

Sending form data via HTTP Post [Objective C]

I have a form data from an iphone app that needs to send HTTP Post variables to a URL.
The thing is, I've been told not to use setHTTPBody, but am unsure of how else to do it as every example I see uses setHTTPBody; even those that use POST methods.
To make things matters a little more complicated, the URL/webpage requires a submit=true and action=enquiry in the post variables.
Here's what I have so far.
NSString *formContactName = [self contactName];
NSString *formEmail = [self email];
NSString *formPhone = [self phone];
NSString *formComments = [self comments];
// The above data is fine, as explored here.
NSLog(#"formContactName = %#", formContactName);
NSLog(#"formEmail = %#", formEmail);
NSLog(#"formPhone = %#", formPhone);
NSLog(#"formComments = %#", formComments);
// Setup request
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:advertURL]];
[request setHTTPMethod:#"POST"];
// set headers
NSString *contentType = [NSString stringWithFormat:#"text/plain"];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// setup post string
NSMutableString *postString = [[NSMutableString alloc] init];
[postString appendFormat:#"contactname=%#", formContactName];
[postString appendFormat:#"&email=%#", formEmail];
[postString appendFormat:#"&phone=%#", formPhone];
[postString appendFormat:#"&comments=%#", formComments];
[postString appendFormat:#"&submit=yes"];
[postString appendFormat:#"&action=enquiry"];
// I've been told not to use setHTTPBody for post variables, but how else do you do it?
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
// get response
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >=200 && [urlResponse statusCode] <300)
{
NSLog(#"Response ==> %#", result);
}
[result release];
[error release];
I always get a 200 result, which is good. But the response back indicates that the Post variables are not getting through.
The response back has a field in it called "enquirysent" and its always blank. If the Post variables are successful, it should return a "1" or true statement.
"enquirysent": ""
Therefore, my question is: How do I force the HTTP-POST variables in the above request?
Thanks.
you can use ASIHTTPRequest to simplify:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Ben" forKey:#"first_name"];
[request setPostValue:#"Copsey" forKey:#"last_name"];
[request setFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photo"];