I'm working on an iPhone app that needs to load data from my server in JSON or XML format. Since the app is free, I get huge amount of data and I get crash when launching app due to the long time when loading the data. So I understand that I should not get "all" the JSON at once but I have to load the data "pagened" [ little by little ] ..
I found this project that suits well my needs but can't get succes to modify it to my need :
https://github.com/nmondollot/NMPaginator
The project tooks Twitter api as a data source, what if I need to deal with a simple php file that returns JSON formatted data?
nb: I tried to contact the project developer after I tried to modify, but didn't get answer until now.
Thanks.
The easiest solution could be to just download the data in another thread. This can be done in many ways but one way to do it is by using grand central dispatch (GCD).
Something like this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSURL *url = [NSURL URLWithString:#"Your_URL"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:req
queue:[NSOperationQueue currentQueue]
completionHandler:
^(NSURLResponse *res, NSData *data, NSError *err) {
// Convert the data to appropriate object
NSString* myString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//You would probably deserialize the json here
//self.tableViewArray = serialiedObjects;
dispatch_async(dispatch_get_main_queue(), ^{
//Reload table view
[self.tableView reloadData];
});
}];
});
Related
I use NSURL to load some things from an MySQL Database. Sometimes this is very slow and the app stops running because the Database is not answering.
I thought I could make a timeout, so after e.g. 3 seconds, the app stops loading the NSURL and tries again or does something else like an UIAlertView.
Please help me!
Jannes
PS: I use this code to load these things from the Database:
-(void) loadSomething {
NSError *error;
NSString *urlString = #"http://someip/App/somefile.txt";
NSURL *url = [NSURL URLWithString:urlString];
#try {
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
}
#catch (NSException *exception) {
NSLog(#"Error");
}
Your request is a synchronous request and this type of request freezes the ui, you should use an asynchronous request to prevent the freeze.
Here is a tutorial on request asynch / synch that should help you.
Otherwise perhaps think to use the framework " AFNETWorking " it greatly simplifies the use of NSURLConnection and NSURLRequest
I have the following doubts about the JSON data returned from using both "GET" versus "POST" request. In the following URL JSON DATA, the data is not always updated based on the server changes (eg: database). For example, if I delete all the suggestion records from the database when I had 3 previously, it still returns 3 suggestion records in my JSON response body when I call dataTaskWithRequest.
However, if I change to POST, then the JSON response body will always be updated with the actual records from the server. In my server code (Using CakePHP), I did not check for post or get data. Actually, it was intended to be a GET method, but for some reason, only POST method seems to always fetch the most up to date data from JSON as opposed to GET.
Below is my code from my iOS client, but I'm not too sure if its very useful. I was wondering if there is a cache issue for GET request as opposed to POST request? However, I tried disabling cache for NSURLSessionConfig but it had no impact.
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
The code base is below:
NSString *requestString = [NSString stringWithFormat:#"%#/v/%#.json", hostName, apptIDHash];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if (!error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (httpResp.statusCode == 200) {
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
[self printJSONOutputFromDictionary:jsonObject];
if (!jsonError) {
block(jsonObject, nil);
}
else{
block(nil, jsonError);
}
}
else{
NSError *statusError = [self createServerUnavailableNSError:httpResp];
block(nil, statusError);
}
}
else{
block(nil, error);
}
}];
[dataTask resume];
In the above code fragment, the JSON body is always showing outdated data.
I really want to understand the issue, and would really appreciate if anyone could explain this issue for me.
Try adding the following request header:
[req addRequestHeader:#"Cache-Control" value:#"no-cache"];
I encountered the same problem as you and adding the above code solved the problem for me.
Taken from ASIHTTPRequest seems to cache JSON data always
I am using the following code to insert in mysql table from Xcode app via php,
-(void)insertDetails:(NSString *)userEmail loginType:(int)type{
login_email = userEmail;
NSString *strUrl = [NSString stringWithFormat:#"http://localhost/insertLoginDetails.php?userEmail=%#&login_type=%d",userEmail,type];
NSData *dataUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:strUrl]];
NSString *strResult = [[NSString alloc] initWithData:dataUrl encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResult);
}
This uses the GET method, can anyone please tell me how to use the POST method for the above process.
Thanks in advance.
Regards,
Neha
Make use of NSUrlconnection to call the webservice
Use requestWithURL:(NSURL *)theURL
If you need to specify a POST request with HTTP headers make use of NSMutableURLRequest with these methods
-(void)setHTTPMethod:(NSString *)method
-(void)setHTTPBody:(NSData *)data
-(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
There are lots of tutorial avaiable about NSURLConnection. like Fetching data with GET,POST methods by using NSURLConnection
Fetching data with GET,POST methods by using NSURLConnection have expalined how to fetch data from server synchronously and Asynchronously.
Im currently developing and IOS application, For security purposes I would like to know how I can make the app send the device "UDID" to a server.
So basically I need to know how to make the device "fetch" the udid and then take the udid and send it to a server as a "request".
If the UDID is "registered" in the MYSQL database, then the server will send back a confirmation.
Besides finding out how to get the udid, I may need additional help setting up the mysql database :$
Thanks!
You can get the UUID of an iOS device using: CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *udidString = (NSString *) CFUUIDCreateString(NULL, udid);
(Apple dont like you to use the UDID).
As far as posting it to a server, I suggest using a JSON post method, and recording the success. A good JSON library is SBJson which can be found here. Youll need to create a HTTP post, get the response data, and use SBJson library to parse the response.
EDIT: OR instead of SBJson, as Carbonic acid kindly pointed out, you can use NSJSONSerialization. Also, as pointed out by Naz Mir, new UUID method used.
Edit:
[[[UIDevice currentDevice] identifierForVendor] UUIDString] is not deprecated as I stated. Please go through the links below for information.
Getting UDID as stated above NSString *uuididentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; is deprecated and Apple no longer allows it. If your aim is to uniquely identify a device you can use SecureUDID or OpenUDID
I have used OpenUDID sometime back in one of our apps and using it is as simple as -
#import "OpenUDID.h"
[OpenUDID setOptOut:NO];
self.openUDID = [OpenUDID value];
Once you have the required value sending it to the server is trivial. You can use iOS networking library like AFNetworking to send and receive data. For example,
#import "AFHTTPRequestOperation.h"
NSURL *url = [NSURL URLWithString:#"Your sever URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *postString = [NSString stringWithFormat:#"&UDID=%#", self.
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
AFHTTPRequestOperation *httpOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *httpOperation, id responseObject) {
//handle server response here
NSLog(#"%#", [httpOperation responseString]); //this contains the servers response
}failure:^(AFHTTPRequestOperation *httpOperation, NSError *error) {
//handle server errors here
NSLog(#"error: %#", [httpOperation error]);
}];
I am running a phpmyadmin database and have made a table with 3 columns. Username, Password and Age. In Xcode ive made a login app that uses the username and password to login with
NSString *strURL = [NSString stringWithformat:#"http://localhost/database/login.php?username=%#&password=%#", usernamefield.text, passwordtextfield.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if ([strResult isEqualToString:#"1"])
This code works fine!
Is it then possible to show the third column in the database (AGE) in a text label when pressing login? so the Age of the user logged in will be displayed in a text label at the top bar of the app?
There's a lot that you could do to improve the security (not sending the password as a parameter of a GET request, it might (will) end up on some log somewhere unprotected), reliability (your script might not be the only thing that need to run on localhost) or the responsiveness (not doing a synchronous call) of that code.
But, starting with that code as a minimalistic starting point, you could configure your php script to respond with the age value and dispatch this value to a textfield/window title/whatever you want.
But then how to check if the user is correctly connected? Your script running on localhost could respond with bad authentication with a string.
For example:
NSString *strURL = [NSString stringWithformat:#"http://localhost/database/login.php?username=%#&password=%#", usernamefield.text, passwordtextfield.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if ([strResult isEqualToString:#"auth_error"]){
// do something
} else {
[window setTitle:strResult]
}
But that's really a start.
After that, you might be interested to use JSON to answer the request and then read it with NSJSONSerialization, making your script a little more reliable and RESTful.