1

I want to do NSURLConnection for User login, I am using like this.

-(void)userLogin {

     NSString *urlString;

     urlString =[NSString stringWithFormat:@"http://sampleAPI.com/api/v1/users];

      NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
     [request setURL:[NSURL URLWithString:urlString]];

     [request setHTTPMethod:@"GET"];

   NSString *boundary = @"---------------------------14737809831466499882746641449";
   NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
   [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

     NSMutableData *getbody = [NSMutableData data];
    [getbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [getbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n%@", @"john89"] dataUsingEncoding:NSUTF8StringEncoding]];
   [getbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


   [getbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"password\"\r\n\r\n%@",@"123456"] dataUsingEncoding:NSUTF8StringEncoding]];
    [getbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];




    [request setHTTPBody:getbody];



   conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
    webData = [NSMutableData data];
     }
    }

But it is not giving the proper result. Error comes like this.

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0xb45ad30 {NSErrorFailingURLStringKey=https://dev.verificient.com:8001/api/v1/users, NSErrorFailingURLKey=https://dev.verificient.com:8001/api/v1/users, NSLocalizedDescription=The network connection was lost., NSUnderlyingError=0xc3dac70 "The network connection was lost."}

Where I am making the mistake ?

Nithin M Keloth
  • 1,575
  • 1
  • 20
  • 35
  • You can't send the parameters for a GET method in the body of the request. It has to be something like: `http://sampleAPI.com/api/v1/users?username=john89&password=123456`. Also you shouldn't use GET for things like that. See this answer: http://stackoverflow.com/questions/3477333/what-is-the-difference-between-post-and-get – Ivan Genchev Mar 21 '14 at 18:03
  • You actually CAN send parameters for a GET request in the body of the request, however, the standard HTTP spec and all web services following those standards will not accept it. That said, you'll certainly need to move your "form data" to URL parameters as @Ivan Genchev specified. If you provide the docs or some description of the API endpoint I'll add an answer with a code example. – Grant Amos Mar 21 '14 at 19:25
  • 1
    @Enragedmrt The HTTP 1.1 spec does not prohibit to define a body for a GET method. One can even specify a URI for a GET request having a query component AND a body - or no query param and just a body. Query parameters in the URI are orthogonal to the HTTP method. How this data is interpreted depends on the service, though. – CouchDeveloper Mar 21 '14 at 19:36
  • 1
    Composing a multipart message is error prone. And, having said this, your multipart message is not correct ;) But instead using a multipart message, you should first explore the API of the service. Note also, that it is unlikely that a GET request can fulfill a login feature - it's more likely a POST request. – CouchDeveloper Mar 21 '14 at 19:39
  • Busted. Lol. It isn't prohibited by the spec and is certainly technically feasible (I've been required to do so). What I should have said was that it's unlikely a web service would expect parameters in the body of a GET request, but instead I brought the HTTP spec into it unnecessarily and without much knowledge about it. Thanks for correcting me :). – Grant Amos Mar 21 '14 at 19:46
  • Quoting an answer from this: http://stackoverflow.com/questions/978061/http-get-with-request-body question - `Yes, you can send a request body with GET but it should not have any meaning. If you give it meaning by parsing it on the server and changing your response based on its contents you're violating the HTTP/1.1 spec.` – Ivan Genchev Mar 22 '14 at 13:18

6 Answers6

3

Here's an example of formatting an HTTP Get request using NSURLConnection:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://sampleAPI.com/api/v1/users?username=%@&password=%@", @"john89", @"123456"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Grant Amos
  • 2,196
  • 15
  • 11
1

I recommend the widely used AFNetworking library (https://github.com/AFNetworking/AFNetworking). A simple GET request with parameters can be constructed like this:

NSDictionary *p = @{@"foo": @"bar"};
[[AFHTTPRequestOperationManager manager] GET:@"http://example.com/resources.json" parameters:p success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error); 
}];
Tijn
  • 518
  • 4
  • 7
1

Here is a simple example of something I have used recently. Hope it helps!

//data that will be posted to database
NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",[[userNameField text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [[passWordField text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSData *dataToSend = [NSData dataWithBytes:[post UTF8String] length:[post length]];

//create a URL request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://127.0.0.1/login.php?"]];

//set method to use and send data
[request setHTTPMethod:@"POST"];
[request setHTTPBody:dataToSend];

//get response from server
NSURLResponse* response;

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSString *serverOutput = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];

if([serverOutput isEqualToString:@"Yes"])
{
    //do nothing and allow view to change

} else {

    //create alert and inform user that login failed
    UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Fail" message:@"Invalid Access" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];

    [alertsuccess show];
}

here is a simple PHP file.

<?php
$username = $_POST['username'];
$password = $_POST['password'];

$hostusername = "root";
$hostpassword = "root";
$hostname = "127.0.0.1"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $hostusername, $hostpassword) 
  or die("Unable to connect to MySQL");
//echo "Connected to MySQL<br>";

//select a database to work with
$selected = mysql_select_db("whereuapp_data",$dbhandle) 
  or die("Could not select userName");

//execute the SQL query and return records
$result = mysql_query("SELECT username, passWord FROM userData WHERE username = '$username'");
$row = mysql_fetch_array($result);

//echo "Post Name:".$username." Post Password:".$password."<br>";
//echo "ID Name:".$row{'username'}." Password:".$row{'passWord'}."<br>";

// check user level and store in $row
if ($row{'username'} == $username && $row{'passWord'} == $password) 
{
    echo"Yes";
} else {
    echo"No";
}

//close the connection
mysql_close($dbhandle);
?>
user961632
  • 39
  • 8
0

For GET method: You can use following code like::

    NSString * apiURLStr =[NSString stringWithFormat:@"http://example.com/api/v1/updateCredentials?UserName=Brahmam&Passowrd=123&Mobileno=98989898&emailid=Brahmam123444@gmail.com"];
NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:apiURLStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSHTTPURLResponse *response =[[NSHTTPURLResponse alloc] init];
NSError* error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRqst returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseString);

OR

  NSMutableData *responseData;
  NSURLConnection *connection;
  #pragma mark
  #pragma mark -- requestPage
-(void) requestPage{
responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:
                         [NSURL URLWithString:@"http://example.com/RegistrationAPI?UserName=Brahmam&Passowrd=123&Mobileno=98989898&emailid=Brahmam@gmail.com"]];
connection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
#pragma mark
#pragma mark -- NSURLConnection Delegate Mehods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse");
[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   NSLog(@"connectionDidFinishLoading");
   NSError *e = nil;
 dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
 dataResponseDict = [dict objectForKey:@"data"];
if (!dict) {
    NSLog(@"Error parsing JSON: %@", e);
}
[self.tableViewRef reloadData];
}
Mannam Brahmam
  • 2,059
  • 2
  • 20
  • 35
0

api download.h

     #import <Foundation/Foundation.h>

     typedef void(^completionBlock)(NSDictionary *resultDictionary, NSError   
     *error); 
     @interface APIDownload : NSObject
     + (void)sendGetMethod:(NSString *)url key:(NSString *)key 
     withCompletionHandler:(completionBlock)handler;
     @end

api download.m

     #import "APIDownload.h"

     @implementation APIDownload
     + (void)sendGetMethod:(NSString *)url key:(NSString *)key 
     withCompletionHandler:(completionBlock)handler {

     NSLog(@"url %@",url);

     NSLog(@"-------> key %@",key);

    //    if ([key isEqualToString:@"_GoogleAutoComplete"]||[key 
    isEqualToString:@"_GooglePlaceDetails"])

    //        [(AppDelegate *)[[UIApplication sharedApplication]    
    delegate]stopIndicator];

    //    else

    //        [(AppDelegate *)[[UIApplication sharedApplication] 
    delegate]starIndicator];

    NSString *encodedUrl = [url 
    stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL 
    URLWithString:encodedUrl]];

    NSURLSessionTask *getMethodtask = [[NSURLSession sharedSession]   
    dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, 
    NSURLResponse * _Nullable response, NSError * _Nullable error) {



    dispatch_async(dispatch_get_main_queue(), ^{

    NSLog(@"sendGetMethod - sendAsynchronousRequest - Completion Block");

        //            [(AppDelegate *)[[UIApplication 
    sharedApplication]delegate]stopIndicator];

        if (error)

        {

            //[k_AppDelegate showAlertwithTitle:LocalizedString(@"Sorry!") 
      message:error.localizedDescription buttonTitle1:LocalizedString(@"OK") 
      buttonTitle2:@""];      
        }

        else if (data == nil)

        {

            // [k_AppDelegate showAlertwithTitle:LocalizedString(@"Error!")
          message:LocalizedString(@"The specified server could not be 
       found.")  buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];

        }

        else

        {

            NSDictionary *encodeDictionary = [NSJSONSerialization 
       JSONObjectWithData:data options:NSJSONReadingMutableLeaves 
       error:nil];



            if (![encodeDictionary isEqual:[NSNull null]] && 
      encodeDictionary != nil)

            {

                if(handler)

                {

                    handler(encodeDictionary, nil);

                }

                else if([[encodeDictionary objectForKey:@"status"] 
       integerValue] != 1)

                {

                    //[k_AppDelegate 
        showAlertwithTitle:LocalizedString(@"AlertTitle") message:
        [encodeDictionary objectForKey:@"message"] 
        buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];

                }

            }

            else

            {

             //[k_AppDelegate showAlertwithTitle:LocalizedString(@"Error!")
       message:LocalizedString(@"The specified server could not be found.")  
       buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];

            } 
        }
      });
    }];
    [getMethodtask resume];
    }
    @end
0

view 1

#import "ViewController.h"
#import "APIDownload.h"
#import "TableViewCell.h"

@interface ViewController ()
{
NSMutableArray *array;

}

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

   [APIDownload sendGetMethod 
    @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?
    location=11.021459,76.916332&radius=2000&types=atm&senso
   r=false&key=AIzaSyD7c1II   D7zDCdcfpC69fC7CUqLjz50mcls" key:@"ATMAPI" 
   withCompletionHandler:^(NSDictionary *resultDictionary, NSError *error) {


    //NSLog(@"Result---> %@",resultDictionary);
    array = [[NSMutableArray alloc]init];

    array = [[resultDictionary objectForKey:@"results"] mutableCopy];

        NSLog(@"--->%@",[[resultDictionary 
      objectForKey:@"results"]valueForKeyPath:@"geometry.location.lat"]);
     NSLog(@"--->%@",[[resultDictionary 
     objectForKey:@"results"]valueForKeyPath:@"geometry.location.lng"]);

    //       NSLog(@"---> %@",[[array valueForKey:@"id"] objectAtIndex:0]);
    //         NSLog(@"---> %@",[[array valueForKey:@"name"] 
    objectAtIndex:0]);
     //
        [_tableView reloadData];

    //            NSURL *url =[NSURL URLWithString:[[array 
    valueForKey:@"icon"]objectAtIndex:0]];

    //            NSData *data =[NSData dataWithContentsOfURL:url];
    //            _imgView.image =[UIImage imageWithData:data];

    }];
     }

#pragma mark-UITableView Datasourc

  -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
   {
   return 1;
   }
   -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
   (NSInteger)section
   {
   return array.count;
    }

   -(UITableViewCell *)tableView:(UITableView *)tableView 
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
   static NSString *cellid=@"tablecell";



TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
cell.idLabel.text =[[array valueForKey:@"id"]objectAtIndex:indexPath.row];
cell.nameLabel.text =[[array 
valueForKey:@"name"]objectAtIndex:indexPath.row];
 // cell.collectionId.text=[[array    
 valueForKey:@"opening_hours"]objectAtIndex:indexPath.row];

  NSURL *url =[NSURL URLWithString:[[array 
valueForKey:@"icon"]objectAtIndex:0]];

NSData *data =[NSData dataWithContentsOfURL:url];
cell.imgView.image =[UIImage imageWithData:data];


cell.deleteBtn.tag=indexPath.row;

[cell.deleteBtn addTarget:self action:@selector(deleteItem:) 
forControlEvents:UIControlEventTouchUpInside];


return cell;


}

-(void)deleteItem:(UIButton *)sender
{
[array removeObjectAtIndex:sender.tag];
[self.tableView reloadData];
 }
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)deleteBtn:(id)sender
 {
NSMutableArray *removearray =[NSMutableArray array];
for(int i=0; i<array.count; i++)
{
    TableViewCell *cell =[_tableView cellForRowAtIndexPath:[NSIndexPath 
indexPathForRow:i  inSection:0]];
    if (cell.checkbox.isSelected ) {
        [removearray addObject:array [i]];

    }
    [array removeObjectsInArray:removearray];
    [_tableView reloadData];

   }
   }

    @end
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Donald Duck Feb 03 '17 at 16:54