Xcode connect to the MS SQL database - ios

I have an existing database up and running on the remote MS SQL server, and I want to be able to communicate and interact with that database from Xcode. I am writing an application for OS X in Swift, and the data that the application should use, is stored in that remote database.
The problem is, I can't seem to find any Swift library that could connect to the MS SQL server based database. So far, I have only found this open-source library: SQLClient in Objective-C, but it's quite difficult to have it set, especially as I am not familiar with the Objective-C.
Also, I keep seeing this Core-Data library being mentioned anytime there is some communication with the database, but as far as I understand Core-Data doesn't know how to connect to the MS SQL database.
Does anyone have any experience in connecting the Xcode Swift app to the remote MS SQL database? How should one do this? Any kind of advice is more than welcome, because right now I am kind of stuck with this problem.

The ideal way is to write webservices in any serverside language such as php, asp etc. The webservices will communicae with your mysql database and you swift code will communicate to the webservices.

I suggest to write a webservice with php for example to consume mysql data and provide a json/xml response : this is an example of code that can help you to getdata from Database and parse it to json .
function getOneAdminByUserName($cin){
require('connect.php');
//fetch table rows from mysql db
$sql = "SELECT * FROM `admin` WHERE cin= '".$cin."'";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
if(mysqli_num_rows($result)>0){
$myArray = array();
while($row =mysqli_fetch_assoc($result))
{
array_push( $myArray , $row);
}
return json_encode($myArray);
//return json_encode(mysqli_fetch_assoc($result));
}
else{
return "no";
}
Then you can consume service on your ios app with AFnetworking
NSURL *URL = [NSURL URLWithString:#"http://example.com/resources/123.json"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

It's really bad for an application (mobile, web, any client) to directly have access to any database for security issues. Clients really should not be accessing the database, which is often holding very private/secure data. It opens up vulnerabilities (i.e., sql injection attack).
A set of web services written in php or java or some back-end technology is a more secure, scalable system. These web services can connect to the database and retrieve data. Your iOS application can call the web services and receive the data..for example in the form of XML or JSON.
So better you to use webservice.
Also coredata can use below 4 persistant store

Related

REST API Request for Mobile App

I am creating an App for iOS/Andriod using appery.io (basically a phonegap type website that uses a WYSIWYG) that will basically be a calendar for upcoming TV episodes. Users will select the shows they want to watch and the calendar/list in the App will be populated with the upcoming episodes.
For this, I am trying to use an api called thetvdb.com. However, I have only basic knowledge of databases and even less with API usage. Thetvdb has some documentation for using their API, however, it is difficult to understand and translate into the appery.io form I am using to get requests.
Using their API requires a key, which I already have. I am just not sure what to put for the settings, and request fields. The main one I need to figure out is the URL under settings first. Any help would be greatly appreciated!
Settings:
URL:
Method:
Data Type:
Content Type:
Request:
Not even sure what parameters to use.
Thetvdb.com Documentation (http://www.thetvdb.com/wiki/index.php/Programmers_API)
The appery.io video tutorial I am following (http://www.youtube.com/watch?v=d_iGKRPPsRc&list=PLdUnWwhvJspZXXuozUbly21FBh9AywSa6)
You can using AFNetworking framework. It is easy to use for communication with API.
With GET method, we can do:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
For more information, please read on this website.
https://github.com/AFNetworking/AFNetworking

How do I use AFNetworking/AFOauth2Client with the Imgur API? I simply want to be able to get image information, no logging in

I'm interested in integrating the Imgur API into my app, and it states that in order to get image information (basically the extent of what I need right now) I just need to register my app, no need to log in with user information or anything.
Great, I'm using AFOAuth2Client (specifically this pull request so it works with AFNetworking 2.0). I have my client key and client secret, but I can't seem to figure out how to get to an image.
I try the following code (personal API details removed):
AFOAuth2Client *oauthClient = [AFOAuth2Client clientWithBaseURL:[NSURL URLWithString:#"https://api.imgur.com/"] clientID:#"---" secret:#"---"];
[oauthClient authenticateUsingOAuthWithURLString:#"https://api.imgur.com/oauth2/authorize" parameters:nil success:^(AFOAuthCredential *credential) {
NSLog(#"Yes");
} failure:^(NSError *error) {
NSLog(#"No");
}];
But I always get No outputted. How do I properly authenticate so I can then make calls to the API to get information about an image? (As detailed here.)
As I've been told I don't need OAuth period, I tried the following with AFNetworking 2.0 (to no avail):
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager POST:#"https://api.imgur.com/3/image/1Nf1quS" parameters:#{#"Authorization": #"Client-ID myactualclientidisremoved"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failure");
}];
First, the example is using Imgur API v2 which is old and unsupported. You should be using API v3.
Also note that:
For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests.
from docs at https://api.imgur.com/oauth2 -- so you don't really need OAuth for what you're doing.
There is some example Imgur API code that might help you, listed at https://api.imgur.com/ -- the Android example might be more relevant to you, since it uses Java, but unsurprisingly it comes with all the overhead of an Android project, compared with a plain Java application.

iOS -Windows Azure - MSTable - readWithQueryString

How can I get some items from the table using queries?
I use WindowsAzureMobileServices.framework (iOS app).
I will be very grateful If you can write some examples.
I think it should be something like MySQL queries, but I can not create them correctly (always result = NULL, but the data is there).
self.authService = [AuthService getInstance];
MSTable *imagesTable = [self.authService.client tableWithName:#"images"];
[imagesTable readWithQueryString:#"" completion:^(NSArray *items, NSInteger totalCount, NSError *error) {
NSLog(#"%#",items);
}];
Thank you
In Windows Azure Mobile Services, you can query in two ways: through the REST API or through a custom API.
Querying through the REST API:
The GET verb supports URI parameters conforming to the Open Data Protocol (OData). These parameters allow you to specify filters, order, projections, paging, and other features. The query is not based on SQL syntax, but in the OData syntax, which is tailored for entities served in the REST style.
This is documented in Query records operation and you'll find examples in the form of automated tests in the Mobile Services SDK for iOS: see MSQueryTests.m.
For instance, this sample code:
-(void)testMSQueryInitWithSimplePredicate
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == 'bob'"];
query = [[MSQuery alloc] initWithTable:table predicate:predicate];
STAssertTrue([query.description
isEqualToString:#"$filter=(name%20eq%20'bob')&$inlinecount=none"],
#"OData query string was: %#",
query.description);
}
There is also this example in How to use the iOS client library for Mobile Services:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"complete == NO"];
[table readWithPredicate:predicate completion:^(NSArray *items, NSInteger totalCount, NSError *error) {
//loop through our results
}];
Querying through a custom API:
You can write your own functions that run on the server, take any arguments they need, execute any querying and processing they need, and return any result set. These functions are extremely flexible.
For information on how to develop these functions see Custom APIs in Azure Mobile Services.
To learn how to call these custom functions from iOS refer to Custom API in Azure Mobile Services – Client SDKs and also to this answer.

Survey application with offline capabilities and how to capture the data from multiple ipads to one?

I am trying to build a Survey application where the surveys will be taken offline on multiple ipads and when these ipads are online they are going to upload the data(survey answers) to our servers? I am really struggling how to send the survey to multiple ipads and more importantly to capture from different ipads to one source ?
I need help to clear my architecture part and I need some examples to do the coding part. Do you know anything similar?
What are you ideas?
Many Thanks in advance,
Arda
Create a web server to accept and send survey questions and answers.
I would envision an app that goes like this:
1) Slave iPads makes a HTTP POST request to server asking for the survey
This is usually done using a networking library for iOS like MKNetworkKit or AFNetworking. The general process is to:
create a NSDictionary of key-value pairs to form the HTTP POST request
submit the data through a block construct with completion handler
So something like:
MKNetworkOperation *op = [engine operationWithURLString:#"http://www.mywebserver.com/api/fetchQuestions"
params:nil
httpMethod:#"POST"];
2) Server receives request, grabs all survey questions in database and return JSON encoded questions to slave ipads.
I'm not sure what platform your web server is on but in the past, I used Symfony 2.0 which is a PHP web framework.
It provides very helpful tools like Doctrine (an Object Relational Mapper or ORM) to let me work with my MySQL data as if they're programming objects.
So my general process for fetching data would be something like:
// pseudo php function codes
public function sendSurveyQuestionAction()
{
$repository = $this->getDoctrine()->getRepository('MyAppBundle:Survey');
$query = $repository->createQueryBuilder('query')->getQuery();
$arrObjs = $query->getResult();
$arrObjDatas = NULL;
foreach($arrObjs as $obj)
{
$arrObjDatas[] = $obj->toArray();
}
$response = new Response(json_encode(array('data' => $arrObjDatas)));
$response->headers->set('Content-Type', 'application/json');
$return $response;
}
This would return all survey in JSON format, ready to be parsed by your master iPad app.
3) Users on slave iPads fill in the questions through the app UI and submits. The app saves
the data to disk, checks for a working internet connection before sending data back to server.
Submitting the answer is very similar grabbing the questions, so your iOS code should be something like:
// ------------------------------------------------------------------------------------
// store all question-answers into a dictionary to be submitted as HTTP POST variables
// obviously, you wouldn't create it here, this is just example code, you would likely
// have stored your questions and answers when user presses 'finish' button
// ------------------------------------------------------------------------------------
NSMutableDictionary *paramDictionary = [[NSMutableDictionary alloc] init];
[paramDictionary setObject:#"5" forKey:#"q1"];
[paramDictionary setObject:#"10" forKey:#"q2"];
[paramDictionary setObject:#"15" forKey:#"q3"];
// this helps your web server know how many question-answers to expect, or you could hard code it into your business logic
[paramDictionary setObject:[NSNumber numberWithInteger:3] forKey:#"numberOfQA"];
MKNetworkOperation *op = [engine operationWithURLString:#"http://www.mywebserver.com/api/submitAnswers"
params:paramDictionary
httpMethod:#"POST"];
This will submit your answers for each of your question. You may have noticed I used q1, q2, q3.
These are for your web server code to identify each questions and extract the respective answers from them.
4) Server receives finished answers and commit them to database
So if you were using Symfony 2.0 PHP code, then something like:
// pseudo php function
public function saveAnswersAction()
{
$numOfQA = $_REQUEST['numberOfQA'];
for($i = 0; $i < $numOfQA; $i++)
{
// ----------------------------------------------------------------------
// looping through all the questions such as q1, q2, q3, q4, q5....
// by appending the counter variable to the question identifier
// ----------------------------------------------------------------------
$currentAnswer = $_REQUEST['q'.$i];
// use Doctrine to create new answer entities, and fill in their data
$answerEntity.answer = $currentAnswer;
$surveyEntity->addAnswerEntity($answerEntity);
// mark survey as complete so we can fetch all 'completed' surveys later
$surveyEntity.complete = true;
}
// tell Doctrine to commit changes to MySQL Database
// return HTTP OK status message
}
5) Now all that's left is for your master iPad app to make a HTTP POST request to get all surveys.
The process is the same with your iOS code making a HTTP POST requesting for all 'completed' survey entities from your web server.
The web server grabs them and return them as JSON encoded data.
Your app then receives the completed surveys with question answer like this:
surveys
{
{
questionNumber: 1,
questionAnswer: "5"
},
{
questionNumber: 2,
questionAnswer: "10"
},
{
questionNumber: 3,
questionAnswer: "15"
}
}
Now you use JSONKit to parse this JSON data. You should end up with a NSDictionary from JSONKit.
You can then go something like:
// pseudo code
-(void)displayCompletedSurveys
{
[MKNetworkOperationEngine doRequest:
...
^completionBlock {
// parse JSON data
NSDictionary *surveyData = [JSONKit dictionaryFromJSONData:data)
NSEnumerator *enumerator = [surveyData enumerator];
NSDictionary *currentQuestion = nil;
while([enumerator nextObject] != nil)
{
// do something with each of your question-answer e.g. show it on screen
}
}];
}
Points To Consider
Most of the code above are pseudo-codes. Your final real code would probably be much more in depth.
You'll need to build some master login into your app to prevent everyone from seeing the completed surveys.
Some Extra Information You Should Know
Here are some extra information to help you
JSONKit for fast JSON data decoding from your web server
MKNetworking or AFNetworking to submit your data to your web server
You need to know how to write web services to handle accepting the survey answers. I recommend learning a web framework like Symfony 2.0
Hope that helps.

how to make ruby on rails database api available for a data driven ios app [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Well , I have just started coding in general. I am trying to make an ios social app with basic picture information taking data from a website ( some what of a flickr-clone)
So , the main website will be built on Ruby on rails.
EDIT :
ok so , i want to know when a person uploads a picture , it will have the following entries:
* name
* who took
* location
I was researching about the gem logtrend (https://github.com/gorsuch/logtrend) , i was wondering if I can make a trending feed of sorts using location?
eg: the user selects a tab which shows them the trending pic ( near them (based on his core location) ?? Can we do something like that ?
I don't know anything about Ruby on Rails but I do know to do what you're trying to do (let user upload photos with their name and GPS location to a server, then allow other users to view that photo by downloading it down to their app).
One way you can build the server is to build a web service with Ruby on Rails.
Web Servcie
The web service (your server) does 2 things:
1) Accept a Request
2) Return a Response
With the web service, you accept HTTP POST or GET request, then your server's logic code will parse the "parameters" or "variables" inside the POST or GET.
Once your server has these variables, it can save them to the database (an ORM would really make it easier).
Your web service can then return a response using HTTP Status Code or a JSON formatted response.
Example Scenario
1) iPhone app takes photo and then makes a HTTP POST request to your Ruby server using ASIHttpRequest or AFNetworking.
// ASIExample
-(void)uploadPhotoToServer
{
NSURL *url = [NSURL urlWithString:myUploadWebServiceURL];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// ---------------------------------------------------------------
// setting the POST parameters below
// note: you will need to get the NSData from a UIImage object
// ---------------------------------------------------------------
[request setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
[request setPostValue:fldName.text forKey:#"name"];
[request setPostValue:[NSNumber numberWithDouble:myLatitude] forKey:#"latitude"];
[request setPostValue:[NSNumber numberWithDouble:myLongitude] forKey:#"longitude"];
[request setCompletionBlock:^{
int statusCode = [request responseStatusCode];
if(statusCode == 200)
{
[self alertUploadComplete];
}
}];
[request setFailBlock:^{
NSLog(#"Server error: %#", [[request error] localizedDescription]);
[self alertConnectionProblem];
}];
[request startAsynchronous];
}
2) Server receives the request, parses the data and returns a response
// Symfony Web Framework example (PHP based web framework)
public function uploadPhotoAction()
{
// --------------------------------------------------
// check to make sure all POST parameters are sent
// in the POST request by iPhone app.
// --------------------------------------------------
if(
!isset($_REQUEST['name']
|| !isset($_REQUEST['latitude']
|| !isset($_REQUEST['longitude']
|| !isset($_REQUEST['photo']
)
{
return new Response($this->sendResponse(406, 'Missing POST parameters');
}
else // assumes safe to continue
{
/*
write code to save the your name, latitude, longitude to your database here
*/
/*
save your photo to your server's dedicated photo folder, then store
the file path to the file in your database entry in the above step
*/
return new Response($this->sendResponse(200, 'Photo uploaded'));
}
}
A couple of gems that you could make use of are Devise coupled with OmniAuth for social logins/authentication.
For more gems by categories, check out Ruby Toolbox.
Hope you the best of luck!
Is this achievable through ruby on rails ?
Yes, yes it is.
what gems should I be using ?
Depends upon your approach and featureset.
Also , which gems can be used to make API's to feed the IOS app ?
I think you're misunderstanding what an API is. The API is HOW the client will interact with the host.
I would suggest you investigate using JSON to communicate between your IOS app and your Web app. Both IOS and Ruby/Rails are very capable of supporting JSON and it is relatively lightweight.
Also, you need to define, in detail, what the IOS application is going to do where it needs interaction with the Web app.
Example
IOS App (IA) will save a picture to the Web App (WA).
IA may save the same picture to WA (overwriting)
IA will be told if WA is full
IA will log into WA
IA can log out from WA
IA can change password on WA
WA will reject commands from a non-logged in IA
IA can retrieve user's pictures from WA
IA can retrieve any other user's pictures from WA
etc.
Now, for each one, you design the API to support that function.

Resources