Reputation: 1595
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 ?
Upvotes: 1
Views: 9748
Reputation: 27
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
Upvotes: 0
Reputation: 27
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
Upvotes: 0
Reputation: 2283
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&[email protected]"];
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&[email protected]"]];
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];
}
Upvotes: 0
Reputation: 39
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);
?>
Upvotes: 1
Reputation: 568
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);
}];
Upvotes: 1
Reputation: 2256
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];
Upvotes: 3