Storing an iOS app's data remotely [closed] - ios

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

Related

How to remove everything from core data (All NSObject)? [duplicate]

This question already has answers here:
Core Data: Quickest way to delete all instances of an entity
(29 answers)
Closed 6 years ago.
Can any one tell me how to remove all the NSObject of CoreData at a same time ?
Currently i have done with for loop but i think it is not good way also taking more time when size of data is more, Thanks in advance.
You can still delete the file programmatically, using the NSFileManager:removeItemAtPath:: method.
NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
Then, just add the persistent store back to ensure it is recreated properly.
The programmatic way for iterating through each entity is both slower and prone to error.
Just removing the store and recreating it is both fast and safe, and can certainly be done programmatically at runtime.

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

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

IOS: Using stringWithContentsOfURL when network is unavailable

In this code poll from within my app for a reachable network
("http://soxxx9.cafe24.com/event.php")
NSString * szURL =[NSString stringWithFormat:#"http://soxxx9.cafe24.com/event.php"];
NSURL *url = [NSURL URLWithString:[szURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];
NSString *strData;
while(1)
{
NSError *error = nil;
strData = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
if(!error)
break;
//String data is not owned by me, no need to release
}
If you have a better way, please teach me.
This code seems to be heavily power consuming when network is out : you'll try million times to download something that is unreachable...
Have a look at the Reachability class, provided by Apple (http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html). You'll find ARCified versions on gitHub (https://github.com/tonymillion/Reachability for example).
The idea is to register for notifications about the network reachability.
So, in your code :
Check network resource availability before retrieving the string you want.
If this is available, use your code WITHOUT the while(TRUE)
Check your string for any error while retrieving it client side = in your code
If the network is not available, you'll have to inform the user that network is unreachable, and register for reachability notifications to retrieve your string as soon as it is reachable again for example.
You should a class to handle the connection for you. This way you have more control of what's going on with it. MKNetworkKit is a solution, you can check it here.

What are alternatives to NSURLConnection for chunked transfer encoding

I've checked for other questions relevant to this, but the only answer is "Use ASIHTTPRequest" as this is no longer being developed I wanted to ask what alternatives people are using, whilst working on our SDK I came across a lot of strange behaviour in NSURLConnection when receiving data from the server.
We tracked it down to the fact that NSURLConnection doesn't deal well with responses in chunked-encoding. Or at least so we read in this question here NSURLConnection and "chunked" transfer-coding
Some developers we were talking to say it gets better in iOS 5, we need to make sure that our SDK is backwards compatible with iOS 4.3 at least.
I want to confirm this is infact an issue in NSURLConnection, and how people are dealing with it.
All the alternatives I've found so far are based off of NSURLConnection and I'm assuming as such will have the same flaw. ASIHTTPRequest did in fact work because it's based a little lower than NSURLConnection, but were looking for alternatives in the knowledge it's no longer supported.
A list of other libraries looked at are:
Restkit,
ShareKit,
LRResty,
AFNetworking,
TTURLRequest
I'm aware there are similar questions here Is RESTKit a good replacement for ASIHTTPRequest? and here ASIHTTPRequest alternative But both of the solutions are based off NSURLConnection.
EDIT: I noticed I pointed to the wrong question at the start of my post, so thats updated. It points to a thread from 2008, and i've seen similar ones but none that are recent.
Chunked transfers are supported by NSURLConnection. I use them.
Define some props:
NSMutableData * responseData;
NSURLConnection * connection;
Establish a connection
NSURL *url = [NSURL URLWithString:#"...."];
self.responseData = [[NSMutableData alloc] initWithLength:0] ;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
Register your callback method for connection established
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// You may have received an HTTP 200 here, or not...
[responseData setLength:0];
}
Register your callback method for "chunk received"
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString* aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"This is my first chunk %#", aStr);
}
Register your "connection finished" callback:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}
And finally, register you "connection failed" callback:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Something went wrong...");
}
Just to chime in for the next person that gets here and still can't get NSURLConnection to work with chunk encoded data.
NSURLConnection will work with chunked encoding, but has non-disclosed internal behaviour such that it will buffer first 512 bytes before it opens the connection and let anything through IF Content-Type in the response header is "text/html", or "application/octet-stream". This pertains to iOS7 at least.
However it doesn't buffer the response if Content-Type is set to "text/json". So, whoever can't get chunked encoded NSURLConnection responses to work (i.e. callbacks aren't called) should check the response header and change it on the server to "text/json" if it doesn't break application behaviour in some other way.
There aren't any alternatives I'm aware of.
All the other libraries are built on top of NSURLConnection. Though you could use one of the non-iOS libraries, eg. libcurl.
ASIHTTPRequest is the only library I'm aware of that's built on top of the CFNetworking layer instead. This was (perhaps indirectly) the main reason the original developer stopped working on it - because it doesn't use NSURLConnection it has a lot of code.
It's probably not strictly correct to say that ASIHTTPRequest is no longer supported. It is true that the original developer no longer works on it, but if you look at the github commits you'll see it is still being worked on by other people. A lot of people still use it, for various reasons, myself included.
Having said all that, to go back to the problem you have: I'm not sure a 3 year old thread is necessarily a definitive reference to prove that a 1 year old release (ie. iOS 4.3) of NSURLConnection doesn't support chunked transfers. Chunked transfers are used so much on the web that it seems highly unlikely it would have a problem this large and obvious. It's possible there is something very particular to the server that you're using that is causing the issue.

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