newby IOS: unable to redirect url - ios5

This is my first IOS project. Having a tough time getting login to work. The site has a meta_refresh to another url. I've tried to send another request to the url in the meta_refresh but then the app just hangs. I'm sure that I'm doing something wrong but I'm using XCode 4.4 so a lot of the NSURLConnection delegate methods have been deprecated.
Here's what I'm doing:
NSString *urlAsString = baseURL;
urlAsString = [urlAsString stringByAppendingString:#"?user[login]=username"];
urlAsString = [urlAsString stringByAppendingString:#"&user[password]=password"];
urlAsString = [urlAsString stringByAppendingString:#"&origin=splash"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if([data length] > 0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
NSRange obj = [html rangeOfString:#"http-equiv=\"refresh\""];
NSInteger len = obj.length;
} else if([data length] == 0 && error == nil) {
NSLog(#"No data was returned.");
} else {
NSLog(#"Error happened = %#", error);
}
Here's what I'm getting:
Another question is that I've read that I should use asynchronous connection. The trouble is that I need the data scraped from the site to display on the screen. If I display the screen before the data is returned, then I won't have any data -- or am I not understanding how this works?
Thanks.
--Tony

I think that maybe you're a mixing stuff. You're setting a string url with GET values and then you set the HTTPMethod to POST and I don't know if that is going to work fine.
Here's a code that I have to send values with POST:
NSString *post = [NSString stringWithFormat:#"&user_login=%#&user_password=%#&origin=%#,username,password, splash];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:baseURL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

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....:)

Pass username and password in URL for authentication

I want ot pass username and password in URL(web service) for user authentication which will return true and false.I'm doing this as following:
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://URL/service1.asmx"]];
[request setHTTPMethod:#"GET"];
Now, I wanted to know How can I pass my username and password in this URL to make request.
Could any one please suggest or give some sample code?
Thanks.
Try this :-
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName.text];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword.text];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord]]];
[request setHTTPMethod:#"GET"];
Hope it helps you..
NSString *urlStr = [NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord];
[request setURL:[NSURL URLWithString:urlStr]];
To improve the secure , you may use the Http Basic Authentication.
There are answer here.
First off I would not pass a username and password across in a url. You should do this using post.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIMEOUT];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
This is more secure then passing sensitive data across in a url.
Edit
To get the response you can check this out. NSURLConnection and AppleDoc NSURLConnection
You can use a few different methods to handle the response from the server.
You can use NSURLConnectionDelegate
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
along with the delegate call backs:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData");
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
Or you can also use NSURLConnection sendAsynchronousRequest block
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];

NSURLRequest: How to change httpMethod "GET" to "POST"

GET Method, it works fine.
url: http://myurl.com/test.html?query=id=123&name=kkk
I do not have concepts of POST method. Please help me.
How can I chagne GET method to POST method?
url: http://testurl.com/test.html
[urlRequest setHTTPMethod:#"POST"];
try this
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",username.text,password.text];
NSLog(#"%#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#" server link here"]]];
[request setHTTPMethod:#"POST"];
NSString *json = #"{}";
NSMutableData *body = [[NSMutableData alloc] init];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
//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);
}
// create mutable request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// set GET or POST method
[request setHTTPMethod:#"POST"];
// adding keys with values
NSString *post = #"query=id=123&name=kkk";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];

How to send a Get request in iOS?

I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as
[requestObject setHTTPMethod:#"GET"];
Tell me what could be the problem. Also provide me the code if you have.
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Make sure your requestObject is of type NSMutableURLRequest.
Simply call and use:
(void)jsonFetch{
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSError *erro = nil;
if (data!=nil) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];
if (json.count > 0) {
for(int i = 0; i<10 ; i++){
[arr addObject:[[[json[#"feed"][#"entry"] objectAtIndex:i]valueForKeyPath:#"im:image"] objectAtIndex:0][#"label"]];
}
}
}
dispatch_sync(dispatch_get_main_queue(),^{
[table reloadData];
});
}];
[data resume];
}

XML parsing is not working as expected in Objective-C

I am new to iPhone programming, and this is the first time parsing XML file. I have added the url and also hardcoded the XML file into the string, however I am not getting the correct response from the server.
Here is my code:
NSString *post = #"<?xml version=\"1.0\"encoding=\"UTF-8\"?<request><call>GetNewChapters</call><udid>1000000000000000000000000000000000000000</udid><book_id>1</book_id><updatetoken>B20100125054802</updatetoken></request>";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url=[NSURL URLWithString:#"https://www.paisible.com/babelle_api"];
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];
NSString *myStr = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"String Value :%#",myStr);
NSLog(#"theRequest: %#", request);
NSURL *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
Where as webdata is NSMutable data. Please let me know what errors I have made in my parsing code.
Try to replace
NSURL *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
with the following:
NSURLResponse *resp;
NSError *error;
NSMutableData *webData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];
Than, check what "webData" contains.