How can I make a website as an iPhone native application? - iphone

I'm planning to convert my website into an iPhone native application. I'm stuck at the point of how to achieve this.
Initially, I have developed the first screen i.e., LOGIN screen of my application. My server is built in Java. I'm able to send the login credentials to the server and able to see the request on the server. But I'm unable to receive the response from the server for the request I've sent.
A part of my code is:
NSString *post = #"username=";
post = [post stringByAppendingString:username];
post = [post stringByAppendingString:#"&password="];
post = [post stringByAppendingString:password];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://mysite.com/login.action?"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// [request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData data] retain];
NSLog(#"In \"LOGIN()\" : receivedData = %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
NSLog(#"In \"didReceiveResponse()\" : receivedData = %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSString *ReturnStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"In \"didReceiveData()\" : receivedData = %#",receivedData);
NSLog(#"Return String : %#", ReturnStr);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
NSString *urlData;
if (nil != receivedData) {
urlData = [[[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding] autorelease];
}
NSLog(#"In \"connectionDidFinishLoading()\" : urlData = %#",urlData);
[receivedData release];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
[connection release];
[receivedData release];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
How do I develop a LOGIN application?
I'm sending a request successfully to the server but I'm unable to get the response from the server. How can I overcome this issue?

If your experience is with web development you may be interested in looking at NimbleKit for iPhone. It's a simple XCode plugin that allows you to use HTML and JavaScript to develop the entire native application.

Related

How to login a server and get page source on objective-c?

I am trying to login a server by sending my username and password by POST method by NSURLConnection on objective-c but I get this from my NSLog
NSLog:
NSLog:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
What it writes to the console:
404 Not Found
Not Found
Sorry!The page requested was not found.
Why does this happens? Why do I get Not Found page instead of the index page? What do I do wrong? By the way I am trying to connect https not http I don't know does Here is the source code:
#interface ProjectViewController ()
#property NSURLConnection * urlConnection;
#property NSMutableData * responseData;
#end
#implementation ProjectViewController
#synthesize responseData =_responseData;
- (IBAction)LoginButton:(UIButton *)sender {
NSMutableURLRequest *request = nil;
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://loginpage.com"]];
NSString *post = [NSString stringWithFormat:#"sid=%#&PIN=%#", #"username", #"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_urlConnection start];
//[self performSegueWithIdentifier:#"LoginComplete" sender:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//Oops! handle failure here
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
//NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields]; //This would give you all the header fields;
//NSLog(#"%#",headerFields);
}
}
#end
What I just recognized is if I put the part of POST request in to comment it prints the page source to the console but of course I can't send my username and password to the server. I just get the login page's source code but I want to get the source code after I login. Actually I want to redirect to another page by using this session.
This part:
NSString *post = [NSString stringWithFormat:#"sid=%#&PIN=%#", #"username", #"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
is the certificate used on the website self signed? did you try to make the request in a webview to see if it works there? not in an nsurlrequest?
try this response maybe it will give you some hints.

Send HTTP request in objective c

I need to connect to a server without typing "http://". I have to get only the server name and port number from the user. With this, I should be able to connect to a particular server...
In its simplest form, it looks something like this:
- (void)loadHostName:(NSString *)hostName onPort:(NSInteger)portNumber {
responseData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#:%i", hostName, portNumber]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Oh noes! %#", [error localizedDescription]);
[responseData release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Do something with the data, like load it in a web view.
[webView loadData:responseData MIMEType:#"text/html" textEncodingName:#"utf-8" baseURL:nil];
[responseData release];
}
In production code, you should handle cache requests, authentication challenges etc. (see the messages on NSURLConnection), but the above example will send an HTTP request and load it into a web view.
Try this,
NSURL *aUrl = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#:%i", hostName, portNumber]];
NSURLRequest *request = [NSURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
NSString * theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
[resp release];
[err release];
NSLog(#"response: %#", theString);
well you can hardcode HTTP:// with the server name
example
NSString *serverName = "stackoverflow.com";
NSNumber *portNumber = 10;
NSString *finalYrl = [NSString StringWithFormat:#"HTTP://%#:%#",serverName , portNumber];

Web service consuming from iPhone approach

How can I improve this code?
This question is related to What is the last function in iPhone application lifecycle
-(void)LogoutUser
{
int userId = [[GlobalData sharedMySingleton] getUserId];
NSString *soapMsg =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>...", userId
];
NSURL *url = [NSURL URLWithString: #"http://....asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://..." forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [[NSMutableData data] retain];
}
}
-(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
{
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
NSString *theXML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
[theXML release];
[connection release];
[webData release];
}
The problem is that when your application switches to the background state, it no longer receives any network updates. If you require the network call to return before the application enters the background, maybe a synchronous call will help you there.
If you decide to go this route, I also suggest to look at ASIHTTPRequest because those classes will allow you to set a timeout on the synchronous call while the normal NSURLConnection classes won't. Otherwise you risk that your application will be terminated by the iOS if the server does not respond.

How to get data back from webserver with NSMutableURLRequest

I try to build an app for user that enter his data and this data will be post to a webserver for save in a Database. This web server returns some data back like Id or something else.
How I can receive the data the webserver returns back?
The transfer works already with NSMutableURLRequest. But I search for a sollution to read the answer from the web server and display it on a label.
Have a look at the delegate methods of NSURLConnection.
Example of how it could be done. Original source
NSString *post = #"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.someurl.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData data] retain];
}
else
{
// inform the user that the download could not be made
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
NSLog(aStr);
// release the connection, and the data object
[receivedData release];
}

connection didReceiveData called twice while posting a Url in iphone?

I am new to iphone development.I have posted the URL with the user-name and password. I am able to print the data in "connection didReceiveData " method.But i see "connection didReceiveData" method called twice.I don't know ,where i am going wrong. Here is my code
- (void)viewDidLoad {
[super viewDidLoad];
NSString *post = [NSString stringWithFormat:#"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%#&password=%#",#"xxxxxxx",#"xxxxxx"];
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:#"https://secure.school.edu/login/process.do"]]];
[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(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"the data %#",string);
}
The whole HTML page is printed twice in the console.So please help me out.Thanks.
You may receive the response data in chunks, which is why NSURLConnection's documentation states:
"The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load."
Use an instance of NSMutableData for this and only process the complete data once you receive the -connectionDidFinishLoading: message.
As MacOS Developer Library states, connection:didReceiveData can be called multiple times if data is received in chunks. That means you have to save all the chunks in some variable and do data processing in connectionDidFinishLoading method. e.g.
NSMutableData *receivedData = [[NSMutableData alloc] init];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data, for example log:
NSLog(#"data: %#", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
}