I am currently working on an iOS application, and need to store data in a database(not locally). I have done some research on Core Data, but I want to store the data on a web server. Any suggestions?
Thanks
You'd have to do that through some API like a RESTful service. I would do something like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://my.website.com/restService"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[[NSString stringWithString:#"value1=test&value2=test2"] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *urlResponse = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
If you want to store data somewhere on server and you dont have server -you can use one fo the following:
1) iCloud
2) Parse - You can create database on parse.com and use that database directly with Parse API. look at https://parse.com/docs/index for more detail.
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 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.
I have a connection issue that I am unsure how to resolve. I have combed through the documentation for the Errors and for NSURLConnection. This is code that I am using in my iOS version of the same app. It works fine there, but when I brought it to the OS X version of the app, it doesn't work. This is the code:
NSURL* url = [NSURL URLWithString:#"url"];
NSString* data = [NSString stringWithFormat:#"command=retrieve&number=%d", number];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"Starting Command");
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog([NSString stringWithFormat:#"%#",connectionError]);
if ([data length] > 0 && connectionError == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
[self parseResponseFromCommandRequest:data];
});
}
}];
NSLog(#"Ending Command");
The error occurs in the NSURLConnection. The output is:
Error Domain=NSPOSIXErrorDomain Code=1 "The operation couldn’t be completed. Operation not permitted" UserInfo=0x610000279dc0 {NSErrorFailingURLStringKey=url, NSErrorFailingURLKey=url}
url is actually a functioning url, but I replaced it here. Like I said, it works fine on iOS, but not on OS X. Is there a Library that I could be missing that is causing this? Any other ideas?
It could be just a matter of setting up the entitlements to allow access. It looks from the error that it fails because it's not permitted, which would indicate the app sandbox is doing it's job. For NSURL you would normally use bookmarks.app-scope or bookmarks.document-scope.
See: Enabling Security-Scoped Bookmark and URL Access
Depending on how your app is using the NSURL, network entitlements may be worth looking into:
com.apple.security.network.server = Allow Incoming Connections
com.apple.security.network.client = Allow Outgoing Connections
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'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];
});
}];
});