Show JSON content depending on user id iOS - mysql

I want to show the content depending on user id.
The user log-in to the App, after the successful login, he will see the content depending on his id that is retrieved from the JSON file which is connected the the external mysql database.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *jsonURL = [NSURL URLWithString:#"http://api.example.com/page.php?user_id=1"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
self.something = [dataDictionary objectForKey:#"something"];
}
My problem is :
How to make " 1 " in ( user_id=1 ) dynamic, in a way, it will be changed automatically when the user log-in to his account.

Prepare URL dynamically
NSString *userID = #"23";//Get your userID after login
NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://api.example.com/page.php?user_id=%#",userID];

you can use StringWithFormat Method of NSString Class, This methods helps you in creating dynamic NSString Objects,
- (void)viewDidLoad
{
[super viewDidLoad];
NSString userId = #"your user id here";
NSURL *jsonURL = [NSURL URLWithString:[NSString StringWithFormat:#"http://api.example.com/page.php?user_id=%#",userId]];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
self.something = [dataDictionary objectForKey:#"something"];
}

Related

Replace NSURLConnection with NSURLSession to download and parse json feed

I'm a beginner in the area to work with database on iOS. However I could find a way to connect to a MySQL database, download and parse the json feed. Now in iOS 9, I can't use NSURLConnection anymore, that's why I have to replace it with NSURLSession. I saw many tutorials for example this here. So far, I was not able to replace it. Because I'm under time pressure, I can't waste more time to do this. Is here anyone who could help me to replace it?
My code looks exactly like this:
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://myhost.ch/test.php"];
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *_locations = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new location object and set its props to JsonElement properties
Location *newLocation = [[Location alloc] init];
newLocation.idS = jsonElement[#"idStatistic"];
newLocation.temp = jsonElement[#"temp"];
newLocation.hum = jsonElement[#"hum"];
newLocation.date_time = jsonElement[#"date_time"];
// Add this question to the locations array
[_locations addObject:newLocation];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_locations];
}
}
You can try this,
{
NSURL *url = [NSURL URLWithString:#"http://myhost.ch/test.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Result:%#", responseDict);
}];
[task resume];
}

Attaching UITextField to NSUserDefaults

I am a beginner & I am trying to figure out how to upload text from a textfield to a server along with coordinates but I need to add the textfield to userdefaults.
The UITextfield is in my ViewController, while the coordinates & post to server are in a separate object class.
A tutorial or sample code will be very helpful.
Below, I have attached the relevant code I am using to upload the coordinates.
What I need is help on adding and uploading text from UITextfield in another class to the code below.
Singleton.m
#implementation Singleton {
CLLocation *location;
CLLocationManager *locationManager;
NSMutableData *responseData;
}
- (id)init {
if (self = [super init]) {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setDouble:location.coordinate.latitude forKey:#"latitude"];
[userDefaults setDouble:location.coordinate.longitude forKey:#"longitude"];
[userDefaults synchronize];
}
return self;
}
- (void) timerDidFire:(NSTimer *)timer
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (([userDefaults doubleForKey:#"latitude"] != location.coordinate.latitude) || ([userDefaults doubleForKey:#"longtitude"] != location.coordinate.longitude)) {
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"http://setslocation.php"]];
NSDictionary *requestData = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSString stringWithFormat:#"%f", location.coordinate.longitude], #"longitude",
[NSString stringWithFormat:#"%f", location.coordinate.latitude], #"latitude",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
[userDefaults setDouble:location.coordinate.latitude forKey:#"latitude"];
[userDefaults setDouble:location.coordinate.longitude forKey:#"longtitude"];
[userDefaults synchronize];
}
}
first save your textfield value to NSUserDefaults and synchronize. You can get your value any where in your project from NSUserDefaults.
set value like:
[[NSUserDefaults standardUserDefaults] setObject:#"your textfield value" forKey:#"your key name"];
[[NSUserDefaults standardUserDefaults] synchronize];
get value:
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"your key name"]);
make sure you write same key name.

How to download html file from server (not local) in NSString

I have a html file on some server. The html file only contains text no photo's or anything else.
What I want to do is download the html file and put the text into a NSString.
Is this possible?
I found some code a few minutes ago:
NSURL *url = [NSURL URLWithString:#"http://www.example.com/file.html"];
NSString *text = [[NSString alloc] initWithContentsOfURL: url
encoding: NSUTF8StringEncoding
error: nil];
But did not work
Try this :
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval: 20];
NSError *requestError;
NSHTTPURLResponse *response = nil;
// Send request synchronously.
NSData *responseData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &requestError];
// Get the json string reponse.
NSString *stringResponse = [[NSString alloc]initWithData: responseData
encoding:NSUTF8StringEncoding];

Passing param in URL to get json back in IOS

Sorry i am really beginner in IPhone development,i am pulling json data from URL and its pulling and loading data perfectly in UITableView, below is code
- (void)fetchFeed
{
NSString *requestString = #"http://bookapi.bignerdranch.com/courses.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
self.session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.courses = jsonObject[#"courses"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}];
[dataTask resume];
}
Now i want to add filter by instructors, Can any one tell me how i can do that.
Thanks
GET
GET request is just a matter of appending query strings to the API url, for example:
NSString *format = [NSString stringWithFormat:#"http://www.yourapiurl.com?id=%#","123";
NSURL *url = [NSURL URLWithString:format];
NSLog(#"%#",url);
//Creating the data object that will hold the content of the URL
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
POST
-(NSData *)post:(NSString *)postParams{
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.yourapiurl.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postParams length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
return returnData;
}
usage:
NSString *postString = [NSString stringWithFormat:#"prop1=%#&prop2=%#&prop3=%#",
"value1","value2","value3"];
NSData *JsonData = [self post :postString];
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:JsonData options:NSJSONReadingMutableContainers error:nil];
//then parse the JSON

IOS JSON parsing

So i have this JSON:
{"Curs":[{"ID":"AED","Name":"Dirhamul Emiratelor Arabe","Curs":"0.8013","Multiplier":"1","Data":"2011-03-21"},{"ID":"AUD","Name":"Dolarul australian","Curs":"2.9611","Multiplier":"1","Data":"2011-03-21"},{"ID":"BGN","Name":"Leva bulgareasc","Curs":"2.1314","Multiplier":"1","Data":"2011-03-21"},{"ID":"BRL","Name":"Realul brazilian","Curs":"1.7636","Multiplier":"1","Data":"2011-03-21"},{"ID":"CAD","Name":"Dolarul canadian","Curs":"3.0137","Multiplier":"1","Data":"2011-03-21"},{"ID":"CHF","Name":"Francul elvetian","Curs":"3.2484","Multiplier":"1","Data":"2011-03-21"},{"ID":"CNY","Name":"Renminbi-ul chinezesc","Curs":"0.4483","Multiplier":"1","Data":"2011-03-21"},{"ID":"CZK","Name":"Coroana ceha","Curs":"0.1707","Multiplier":"1","Data":"2011-03-21"},{"ID":"DKK","Name":"Coroana daneza","Curs":"0.559","Multiplier":"1","Data":"2011-03-21"},{"ID":"EGP","Name":"Lira egipteana","Curs":"0.4959","Multiplier":"1","Data":"2011-03-21"},{"ID":"EUR","Name":"Euro","Curs":"4.1685","Multiplier":"1","Data":"2011-03-21"},{"ID":"GBP","Name":"Lira sterlina","Curs":"4.7864","Multiplier":"1","Data":"2011-03-21"},{"ID":"HUF","Name":"100 Forinti maghiari","Curs":"1.5354","Multiplier":"100","Data":"2011-03-21"},{"ID":"INR","Name":"Rupia indiana","Curs":"0.0653","Multiplier":"1","Data":"2011-03-21"},{"ID":"JPY","Name":"100 Yeni japonezi","Curs":"3.6213","Multiplier":"100","Data":"2011-03-21"},{"ID":"KRW","Name":"100 Woni sud-coreeni","Curs":"0.2623","Multiplier":"100","Data":"2011-03-21"},{"ID":"MDL","Name":"Leul moldovenesc","Curs":"0.2507","Multiplier":"1","Data":"2011-03-21"},{"ID":"MXN","Name":"Peso-ul mexican\t","Curs":"0.2452","Multiplier":"1","Data":"2011-03-21"},{"ID":"NOK","Name":"Coroana norvegiana","Curs":"0.5286","Multiplier":"1","Data":"2011-03-21"},{"ID":"NZD","Name":"Dolarul neo-zeelandez","Curs":"2.164","Multiplier":"1","Data":"2011-03-21"},{"ID":"PLN","Name":"Zlotul polonez","Curs":"1.0299","Multiplier":"1","Data":"2011-03-21"},{"ID":"RSD","Name":null,"Curs":"0.0404","Multiplier":"1","Data":"2011-03-21"},{"ID":"RUB","Name":"Rubla ruseasca","Curs":"0.1039","Multiplier":"1","Data":"2011-03-21"},{"ID":"SEK","Name":"Coroana suedeza","Curs":"0.4697","Multiplier":"1","Data":"2011-03-21"},{"ID":"TRY","Name":"Lira turceasca","Curs":"1.8665","Multiplier":"1","Data":"2011-03-21"},{"ID":"UAH","Name":"Hryvna ucraineana","Curs":"0.3699","Multiplier":"1","Data":"2011-03-21"},{"ID":"USD","Name":"Dolarul american","Curs":"2.9428","Multiplier":"1","Data":"2011-03-21"},{"ID":"XAU","Name":"Gramul de aur","Curs":"135.0844","Multiplier":"1","Data":"2011-03-21"},{"ID":"XDR","Name":"DST","Curs":"4.678","Multiplier":"1","Data":"2011-03-21"},{"ID":"ZAR","Name":"Randul sud-african ","Curs":"0.4233","Multiplier":"1","Data":"2011-03-21"}]}
And i want to parse it but i am new to this and don't know how. For example how could i get the values from ID.
Here is my code:
#import "DownloadData.h"
#import "JSON.h"
#implementation DownloadData
-(void) connection
{
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://source"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSLog(json_string);
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
//NSLog([json_string description]);
//NSLog([json_string objectForKey:#"Curs"]);
/*
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#",[status objectForKey:#"Curs"]);
}
*/
NSLog(#"test");
//jsondownload=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
#end
Do:
NSDictionary *responseObj = [parser objectWithString:json_string error:nil];
NSArray *statuses = [responseObj objectForKey:#"Curs"];
for (id anUpdate in statuses) {
NSLog(#"ID: %#", [(NSDictionary*)anUpdate objectForKey:#"ID"]);
}