Search code examples
iosobjective-cnsurlconnectionnsurlrequest

NSURLConnection GET method


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 ?


Solution

  • 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];