This is my code.
- (void)loadData:(NSString *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"connection found---------");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"reciving data---------");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"connection fail---------");
[self.pddelegate connectionError];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"data posting done---------");
[self.pddelegate dataPosted];
}
It is not working if url become bigger and give connection fail in logs.
Like
url=#".......order_details&admin=29&tableid=89&waiter_id=18&items=MzQ6MSwxMToxLDMzOjEsNjc6MSwzOToxLDY5OjEsNTY6MSw2ODoxLDg6MSw1NToxLDYyOjEsNzY6MSw0MToxLDIwOjEsNjE6MQ=="
see this SO post for get type request length What is the maximum length of a URL in different browsers?
for sending big string use POST type request instead of GET type.
We have there are two methods for sending data.
1. GET Method : Which is used for fixed length or limited length of string only.
2. POST Method : Which is used to send more string while comparing get method.
I have given the example Using PostMethod.
NSString *post =[[NSString alloc] initWithFormat:#"%#",YourString];
NSURL *url=[NSURL URLWithString:*#"YourURL like www.google.com"*];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
request.timeoutInterval = 60;
NSError *error = nil;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *errStr = _stringEmpty;
#try { errStr = [error localizedDescription]; }#catch (NSException * exception){ }
If any error occur errStr will show the error.
In the past, I have used some URL's that are around 2000 characters in length in iOS with no problem. NSURL, NSURLRequest, and NSURLConnection all managed just fine. If your URL is shorter than that, the problem is probably not due to its length, but instead related to the way the URL is constructed.
Related
I'm trying to view the progress bar while downloading a file. The file is generated through PHP, I'm sending the "Content-length" header, which actually works.
The file is downloaded OK so that's not the problem. Unfortunately I just can't get the file size in order to properly display the progress bar.
Here is my code:
write_to_filename = [issue objectForKeyedSubscript:filename];
NSString *post =[[NSString alloc] initWithFormat:#"user_id=%#&email=%#&password=%#",[userData stringForKey:#"userId"],[userData stringForKey:#"email"],[userData stringForKey:#"password"]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://MY_API_REQUEST"]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setValue:#"application/pdf" forHTTPHeaderField:#"Accept"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
[issueArray writeToFile:[self saveFilePath] atomically:YES];
The NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response {
NSLog(#"%lld",[response expectedContentLength]);
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:write_to_filename];
[_responseData writeToFile:fileName atomically:YES];
write_to_filename = nil;
_responseData = nil;
[[self IssuesOverviewCollection] reloadData];
}
I've tried many different things, unfortunately it's not working and keeps return -1.
This can happen if your server is employing compression (which it can do transparently). You can turn off compression on the server by changing your request Accept-Encoding parameter:
[request setValue:#"identity" forHTTPHeaderField:#"Accept-Encoding"];
I have a class which is used to get data from my server. The data returned from my server is in JSON. For some reason the didReceiveData won't run at all. I have placed NSLogs inside it to test it but it doesn't do anything?
Here is my code:
+(NSJSONSerialization *) getTask:(id)task_id{
NSString *post = [NSString stringWithFormat:#"&task_id=%#", task_id];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://my-server.com/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn){
NSLog(#"Testing");
}
return json;
}
// Log the response for debugging
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(#"test");
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
// Declare any connection errors
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error: %#", error);
}
Thanks,
Peter
getTask: is a class method, which means the self is the class. Therefore the delegate methods must also be class methods.
But note that you cannot return the received JSON from the getTask: method, because NSURLConnection works asynchronously.
You need to start the connection. Try using the initWithRequest:delegate:startImmediately: method:
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
or, just call the start method:
if(conn){
[conn start];
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
hi i am new in ios and i didn't send any call to php till now today i have tried by the following code
-(void)sendRequest
{
NSString *vali = #"$uppl!3r$";
NSString *post = [NSString stringWithFormat:#"key1=%#",vali];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.ddemo3.enerjinet.com/webservices/ios/suppliers.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length: [webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
//greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
it should return me array of 76 records but it returns me <> can anyone please help me ? The web service is ready i need to get the array in response and show it in my table view please help me in doing this
A couple of thoughts:
You NSLog your webData, which will always show <> (as your logging it immediately after instantiated it). I'm not sure why you're logging that.
The question is whether you're seeing that <>, or the NSLog in connectionDidFinishLoading.
I ask that because you are not logging the error in connection:didFailWithError:, if it fails, you'll never know why. You really should log the error in connection:didFailWithError: so you know if it failed, and if so, why:
NSLog(#"%s: %#", __FUNCTION__, error);
In your connection:didReceiveResponse:, you really should look at the HTTP status code:
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200)
NSLog(#"%s: status code is %d; should be 200", __FUNCTION__, statusCode);
}
If it's not 200, you really want to know about that.
You report in one of your comments that you are seeing connectionDidFinishLoading: called, but never having didReceiveData called. That means (unsurprisingly) that there was no data received. So, you should:
Confirm that the connection:didReceiveResponse: reported a statusCode of 200; and
Confirm that the server code is working properly. I could imagine getting the behavior you describe if you had an error in your server PHP code (which is exacerbated by the fact that servers often have display_errors turned off in their php.ini file).
As an aside, if it's possible that the value associated with key1 might contain any reserved characters (as defined in section 2 of RFC 3986), you should percent-escape the string using CFURLCreateStringByAddingPercentEscapes. Thus:
NSString *post = [NSString stringWithFormat:#"key1=%#", [self percentEscapeString:vali]];
Where, per the W3C specs for application/x-www-form-urlencoded, you not only percent escape, but also replace spaces with + characters, thus:
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
Use:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Unless you have a compelling reason not to.
Example (probably non-working):
Note creating postData.
-(void)sendRequest {
NSString *vali = #"$uppl!3r$";
NSString *post = [NSString stringWithFormat:#"key1=%#",vali];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu", [postData length]];
NSLog(#"%#", postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.ddemo3.enerjinet.com/webservices/ios/suppliers.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"data: %#", data);
}];
}
Oh, make life easier, use ARC.
I want to use http Get and Post for getting the request and response of certain URL request,
But i dont know how to use them in objective c..
and Which one will come first Get or Post in establishment of connection.?
how to modify the content and post them back to the server..
Can any one please help me?
for get use :
+(NSMutableURLRequest*)getURq_getansascreen:(NSString*)ws_name {
NSLog(#"%#",ws_name);
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:ws_name] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[urlReq setHTTPMethod:#"GET"];
return urlReq;
}
for post use :
+(NSMutableURLRequest*)postURq_getansascreen:(NSString*)ws_name :(NSString*)service {
NSString *tempUrl = domainURL;
NSString *msgLength = [NSString stringWithFormat:#"%d",[ws_name length]];
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#Service=%#",tempUrl,service]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlReq addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[urlReq setHTTPMethod:#"POST"];
[urlReq setHTTPBody: [ws_name dataUsingEncoding:NSUTF8StringEncoding]];
return urlReq;
}
//Call this in view did load as `
WSPContinuous *wspcontinuous = [[WSPContinuous alloc] initWithRequestForThread:[webService getURq_getansascreen:[webService GetDetails:str_filter]] sel:#selector(WS_GetDetailsLoaded:) andHandler:self];`
//create class WSPContinuous and add these fns..
-(id)initWithRequestForThread:(NSMutableURLRequest*)urlRequest sel:(SEL)seletor andHandler:(NSObject*)handler {
if (self=[super init]) {
self.MainHandler = handler;
self.targetSelector = seletor;
self.urlReq = urlRequest;
[self performSelectorOnMainThread:#selector(startParse) withObject:nil waitUntilDone:NO];
}
return (id)urlReq;
}
-(void)startParse{
NSLog(#"URL CALLING %#",urlReq.URL);
con = [[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
if (con) {
myWebData = [[NSMutableData data] retain];
NSLog(#"myWebData old....%#",myWebData);
}
else {
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
}
//-------------------------------connection-----------------
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[myWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[myWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *thexml = [[NSString alloc] initWithBytes:[myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding];
NSLog(#"xmlDictionary %#",thexml);
[thexml release];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:myWebData error:&parseError];
[AlertHandler hideAlert];
[MainHandler performSelector:targetSelector withObject:xmlDictionary];
}
If you want to start, a better idea would be to do some reading on NSMutableURLRequest and related topics like NSURLConnection.
You get sample code everywhere. Just google it.
Google search -> objective c get and post
and First hit -> Tutorials for using HTTP POST and GET on the iPhone in Objective-C
I am making a synchronous call to the web service and sometimes I get the correct result back from the web service and sometimes I get HTML result indicating a Runtime error. Is there anything on the iOS side I have to do to correctly call the web service. Here is my code:
NSURLResponse *response = nil;
NSError *error = nil;
NSString *requestString = #"some parameters!";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSString *responseData = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
Is it because I am not releasing properly?
you have to set the delegate methods of urlconnection like this
NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setHTTPMethod:#"POST"];
urLConnection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
and the following delegate methods do the trick
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
[receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
you will receive error in the following delegate if connection fails
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{}
you better get the response from the finished connection which tells that all the data been received
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
recievedData //the complete data
}
try this
NSError * error;
NSURLResponse * urlresponse;
NSURL * posturl=[NSURL URLWithString:#"Type your webService URL here"];
NSMutableURLRequest * request=[[NSMutableURLRequest alloc]initWithURL:posturl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:50];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSString * body=[NSString stringWithFormat:#"fbid=%#",userid];
[request setHTTPBody:[body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
NSData * data=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlresponse error:&error];
if (data==nil) {
return;
}
id jsonResponse=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#" json response %#", jsonResponse);
if (![[jsonResponse objectForKey:#"code"] isEqualToNumber:[NSNumber numberWithInt:200]]) {
NSLog( #" successFull ");
this method works for me for more information read facebook documents for ios login
//set request
NSURLRequest *req=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://indianbloodbank.com/api/donors/?bloodgroup=O%2B"]];
NSLog(#"Request-%#",req);
NSError *err=nil;
NSURLResponse *res=nil;
NSData *xmldata=[NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
NSLog(#"Error-%#",err);
NSLog(#"Response-%#",res);
NSLog(#"XmlData-%#",xmldata);
xmldictionary=[XMLReader dictionaryForXMLData:xmldata error:&err];
NSLog(#"XmlDictionary-%#",xmldictionary);
mArray=[xmldictionary retrieveForPath:#"response.donorslist.donors"];
NSLog(#"MutableArray-%#",mArray);
lblname.text=[[mArray objectAtIndex:0]valueForKey:#"name"];
lbllocation.text=[[mArray objectAtIndex:0]valueForKey:#"location"];
lblphone.text=[[mArray objectAtIndex:0]valueForKey:#"phone"];
NSLog(#"%#,%#,%#",lblname.text,lbllocation.text,lblphone.text);
NSLog(#"%#",mArray);
For loop:
for (int i=0; i<mArray.count; i++)
{
Data * don=[NSEntityDescription insertNewObjectForEntityForName:#"Data" inManagedObjectContext:app.managedObjectContext];
don.donorid=[[mArray objectAtIndex:i]valueForKey:#"id"];
don.gender=[[mArray objectAtIndex:i]valueForKey:#"gender"];
don.name=[[mArray objectAtIndex:i]valueForKey:#"name"];
don.location=[[mArray objectAtIndex:i]valueForKey:#"location"];
don.phone=[[mArray objectAtIndex:i]valueForKey:#"phone"];
[app saveContext];
NSLog(#"%#,%#,%#,%#,%#",[[mArray objectAtIndex:i]valueForKey:#"id"],[[mArray objectAtIndex:i]valueForKey:#"gender"],[[mArray objectAtIndex:i]valueForKey:#"name"],[[mArray objectAtIndex:i]valueForKey:#"location"],[[mArray objectAtIndex:i]valueForKey:#"phone"]);
}