How to load data into ViewController from local JSON file [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I'm developing an iPhone app and I need to show stored data in a TableView.
After some research I decided that JSON would be best fit for storing the data. However, I couldn't find any tutorials explaining how to read JSON as a local file rather than
from a remote source, as often is the case.
Any tutorials you could recommend?

First of all: you need to load your local json string. Assuming the jsonstring is inside your project, to load it, first create nsstring pointing to the file:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"THENAMEOFTHEFILE" ofType:#"EXTENSIONOFYOUTFILE"];
second, load the data of file:
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
third, parse the data:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];

You can use NSJSONSerialization for this.
NSError *deserializingError;
NSURL *localFileURL = [NSURL fileURLWithPath:pathStringToLocalFile];
NSData *contentOfLocalFile = [NSData dataWithContentsOfURL:localFileURL];
id object = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile
options:opts
error:&deserializingError];

Related

JSON file parsing gives object name rather contents [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I do have a JSON file I created here: http://www.jsoneditoronline.org/?id=d0b62425c78f98db2398ed558f92e5cf
Simply, I added this file to my project and trying to parse it. For some reason, NSLog line gives me "statement" as a result rather than the statement object. I was expecting it to give me the whole dictionary of statement object instead. I am clearly missing something here. I would appreciate any help.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"math" ofType:#"json"];
NSData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:nil];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"jsonObject is %#", jsonObject); //this gives me the whole JSON object correctly.
for (NSDictionary *dict in jsonObject[#"statements"]) {
NSLog(#"dict is %#", dict);
}
That is screwy JSON. Normally one would expect the value of "statements" to be an array of objects, not just a single object. When you iterate on a dictionary (JSON "object") you iterate through the keys, so you're getting what would be expected.

Combining arrays into a url string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So I'm building an array of url strings using extensions. I have two arrays of extensions and Im a little bit confused on how to combine them.
I am trying to produce an array of string objects with the following format:
http://mywebsite.com/images/places/extention1/extention1
http://mywebsite.com/images/places/extention2/extention2
and so on...
When I try to combine them the way I know how I end up with the full array stuck in the place holders
http://mywebsite.com/images/places/full array1/full array 2
but what I'm really trying to do is build an array of those URL strings from the other two arrays
i know this is super simple but I haven't found any documentation on combining them into a skeleton string.
This would do the trick:
NSMutableArray *urlArray = [[NSMutableArray alloc] init];
NSArray *extensions = #[#"extension1", #"extension2", #"extension3"];
NSString *urlString = #"http://mywebsite.com/images/places/";
for (NSString *extension in extensions) {
NSString *combined = [[urlString stringByAppendingPathComponent:extension] stringByAppendingPathComponent:extension];
[urlArray addObject:combined];
}
There are tons of ways to do this but it could be as simple as:
NSArray *array = [NSArray arrayWithObjects:#"http://mywebsite.com/images/places/extention1/extention1", #"http://mywebsite.com/images/places/extention1/extention2", nil];

Get latest inserted object FatFractal [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm using FatFractal for my backend in a iPhone-app. Been searching the web and FatFractal docs without any luck.
I want to retrieve the latest object in a collection from a grabbag:
NSArray *result = [[Store ff] grabBagGetAllForObj:thread grabBagName:#"messages" withQuery:#"Get the latest inserted object" error:&err];
Probably the best way to do this is to construct the full query yourself and then use the standard getArrayFromUri: method. Taking your example, this would look like:
FatFractal *ff = [Store ff];
NSString *query = [NSString stringWithFormat:
#"%#/messages?sort=createdAt desc&start=0&count=1",
[ff metaDataForObj:thread].ffUrl];
NSArray *result = [ff getArrayFromUri:query];
For more info, see http://fatfractal.com/prod/docs/queries/#sorting-and-limiting-results.

Storing an iOS app's data remotely [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I want my app to store the user's data remotely when they sign up (possibly in a MySQL database). I have seen tutorials about retrieving data through MySQL and JSON, but I cannot seem to find anything about storing data into the MySQL database. Maybe this isn't the best way to do it?
Your question is a bit too vague to be able to answer implementation details, so I give an outline how I would go about the problem:
Determine if you want to create the service yourself or use a cloud data storage provider (some are free and provide iOS libraries. One simple example is Apple's own iCloud).
If you create your own service, use your favorite Web technology. Have a look at Tastypie for example.
Use a RESTful iOS client library such as RESTkit to connect to your service.
If you don't have any specific requirements, I would start by investigating if Core Data + iCloud fits the requirements. That should get you up and running in the shortest time.
I think you can call a .php page from your app like below:
NSString *urlWithGetVars=#"http://www.somedomain.com/somepage.php?var1=avar&var2=anothervar";
NSURL *url = [NSURL URLWithString:urlWithGetVars];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
//turn response data to string
NSString *responseString = [[NSString alloc]
initWithData:responseData
encoding:NSUTF8StringEncoding];
//check if there is any error
if(!error)
{
//log the response
NSLog(#"Response from server = %#", responseString);
}
else
{
//log error
NSLog(#"Error = %#",error.description);
}
And in your somepage.php do the data writing process to the MySql database like below:
<?php
$var1=$_GET["var1"];
$var2=$_GET["var2"];
// Make a MySQL Connection
mysql_connect("yoursitehost", "usr", "pass") or die(mysql_error());
mysql_select_db("yourdb") or die(mysql_error());
// Write var1 and var2 to your mysql table
mysql_query("INSERT INTO your_table (var1,var2) VALUES ('".$var1."','".$var2."')");
or die(mysql_error());
?>
There might be some coding errors if you notice anything wrong let me know...
PS: NSURLConnection sendSynchronousRequest is going to block the user interface so you probably don't want to use it

parse json feeds using jsonkit iOS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to use the JSONKIt found here https://github.com/johnezang/JSONKit to parse through a JSON Feed and put into objective-c objects. I'm new at iOS and don't really know where to start. Are there any good tutorials for using this library?
After googling, I didn't find any tutorials but using JSONKit should be self explanatory.
After downloading your JSON feed using NSURLConnection or ASIHTTPRequest simply create a dictionary of all the objects in the JSON feed like so:
//jsonString is your downloaded string JSON Feed
NSDictionary *deserializedData = [jsonString objectFromJSONString];
//Helpful snippet to log all the deserialized objects and their keys
NSLog(#"%#", [deserializedData description]);
After creating a dictionary you can simply do something like this:
NSString *string = [deserializedData objectForKey:#"someJSONKey"];
And that is the basics behind JSONKit.
JSONKit is much more powerful of course, you can find some of the other things you can do with it in JSONKit.h
I would becareful about making the assumption that objectFromJSONString is returns an NSDictionary, it can very well return an array, or nil, especially if the server returns some rarely used and thought of error.
A more appropriate action would be:
NSError *error;
id rawData = [jsonString objectFromJSONStringWithParseOptions:JKParseOptionNone error:&error];
if ( error != nil ) {
// evaluate the error and handle appropriately
}
if ( [rawData isKindOfClass:[NSDictionary class]] ) {
// process dictionary
}
else if ( [rawData isKindOfClass:[NSArray class]] ) {
// process array
}
else {
// someting else happened, 'rawData' is likely 'nil'
// handle appropriately
}
Without these checks, you could very well end up with a runtime error because the server returned someting unexpected.

Resources