I have this Objective C code:
NSMutableArray *dataArray = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"Dictionary = %#",dataArray);
NSMutableArray *venues = [[NSMutableArray alloc] init];
for (NSDictionary *venueDic in dataArray) {
MapPoint *mapPoint = [[MapPoint alloc] init];
mapPoint.name = [venueDic objectForKey:#"name"];
mapPoint.image_path = [venueDic objectForKey:#"image_path"];
[venues addObject:mapPoint];
NSLog(#"Venue Name: %#", mapPoint.name);
}
But I am struggling to translate the FOR loop. I've spent hours already looking for a solution.
Related
I know how to convert the common NSAttributedString (which has no image) into HTML. I set the Images as NSTextAttachment to NSAttributedString. How could I convert the whole attributed string into HTML?
UIImage *image = [UIImage imageNamed:#"Test.png"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = image;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:htmlString];
NSAttributedString *attstringImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString appendAttributedString:attstringImage];
NSAttributedString *titleContent = (NSAttributedString *)attributedString;
NSDictionary *documentAttributes = #{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [titleContent dataFromRange:NSMakeRange(0, titleContent.length) documentAttributes:documentAttributes error:NULL];
NSString *html = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
Please suggest me with quick answer
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];
}
I need to create a json object in the following format in XCode and I've been using XCode 6.
string json = #"{'user': 'Teva',
'password': 'abc123',
'SourceID':1,
'SiteID':1,
'VariableID':1,
'MethodID':1,
'values':[
['2015-01-29 21:00:00',133.0],
['2015-01-29 22:00:00',134.0]
]}";
I tried NSDictonary approach. However, I'm getting the following output:
This is my code.
- (void)viewDidLoad {
[super viewDidLoad];
NSError *error;
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"user", #"Teva",
#"password", #"abc123",
#"SourceID", #"1",
#"SiteID", #"1",
#"VariableID", #"1",
#"MethodID", #"1",
#"values", #"[2015-01-29 21:00:00, 134.0], [2015-01-29 22:00:00, 135.0]",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:jsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
}
I got the following output:
jsonData as string:
[
{
"abc123" : "password",
"1" : "VariableID",
"Teva" : "user",
"[2015-01-29 21:00:00, 134.0], [2015-01-29 22:00:00, 135.0]" : "values",
"campaignCategory" : "MethodID",
"actionDate" : "SiteID",
"dueDate" : "SourceID"
}
]
Anyone help me to get the right json using objective C. Thanks for your help!
This is the answer that I was hoping to get. I hope it might be useful to someone.
-(void)saveDataValue
{
NSMutableArray *matchArray = [NSMutableArray arrayWithObjects:#"2015-01-29 21:00:00", #(134.0), nil];
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:#"Teva" forKey:#"user"];
[contentDictionary setValue:#"abc123" forKey:#"password"];
[contentDictionary setValue:#"1" forKey:#"SourceID"];
[contentDictionary setValue:#"1" forKey:#"SiteID"];
[contentDictionary setValue:#"1" forKey:#"VariableID"];
[contentDictionary setValue:#"1" forKey:#"MethodID"];
[contentDictionary setValue:matchArray forKey:#"values"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonStr);
}
HAPPY CODING... :)
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
I have this url: http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false
And this code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSMutableDictionary *theDictionary = [responseString JSONValue];
NSLog(#"%#", theDictionary);
[responseString release];
if (theDictionary != nil)
{
NSArray *routesArray = [theDictionary objectForKey:#"routes"];
NSDictionary *firstRoute = [routesArray objectAtIndex:0];
NSArray *legsArray = [firstRoute objectForKey:#"legs"];
NSDictionary *firstLeg = [legsArray objectAtIndex:0];
steps = [firstLeg objectForKey:#"steps"];
}
[tableView reloadData];
}
I want to display every single #"html_instructions" on a uitableview.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.steps count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cachedCell"];
if (cell == nil)
cell = [[[UITableViewCell alloc]
initWithFrame:CGRectZero reuseIdentifier:#"cachedCell"] autorelease];
return cell;
}
What's missing in my code??? Should be some little detail... any help would be GREAT!
I would do it like this:
Create url request with your url
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false"]];
then create NSData structure, that holds response to the request and I converted it to string
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
After that, you load JSON into Dictionary, then to move one level down, pass it to another dictionary (result 1)
NSError *error=nil;
result = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
result1 = [result objectForKey:#"routes"];
result2 = [result1 objectForKey:#"legs"];
Then move it into NSMutableArray
jsonMutArray= [result2 objectForKey:#"steps"];
From there, you just put label into your custom cell attach it as a IBOutlet, synthetize and do in cellForRowAtIndexPath method
cell.yourLabel.text = [jsonMutArray objectForKey:#"html_instructions"];
However, keep in mind, that I'm just begginer, so this might not be the most effective way of doing it :) Good Luck!
Don't you need to be doing something like this in your CellForRowAtIndexPath ?
NSString *cellValue = **WHATEVER VALUE YOU WANT TO PUT IN**;
cell.textLabel.text = cellValue;
return cell;
I don't see you adding your data to the cell.