iOS -Windows Azure - MSTable - readWithQueryString - ios

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.

Related

Xcode connect to the MS SQL database

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

Web crawling in iOS

How to implement Web Crawling technology in iOS.
Any reference/ sample program will help.
Thanks in advance.
Web Crawling
A web crawler (also known as a web spider or web robot) is a program or automated script which browses the World Wide Web in a methodical, automated manner. This process is called Web crawling or spidering. Many legitimate sites, in particular search engines, use spidering as a means of providing up-to-date data.
Generally, iOS is not suitable for Web Crawling, because it is not easily flexible for programmers.
But if you want, it is possible. Basically you will use AFNetworking (or Alamofire, or the System default method) to send web requests. Once you get the response, analyze the text, mainly by using Regular Expression. For example, you can write a category for NSString:
#implementation NSString(StringRegular)
-(NSMutableArray *)substringByRegular:(NSString *)regular{
NSString *reg=regular;
NSRange r = [self rangeOfString:reg options:NSRegularExpressionSearch];
NSMutableArray *arr=[NSMutableArray array];
if (r.length != NSNotFound &&r.length != 0) {
int i=0;
while (r.length != NSNotFound &&r.length != 0) {
NSString* substr = [self substringWithRange:r];
[arr addObject:substr];
NSRange startr=NSMakeRange(r.location+r.length, [self length]-r.location-r.length);
r=[self rangeOfString:reg options:NSRegularExpressionSearch range:startr];
}
}
return arr;
}
#end
And then, you will need to store your data. I recommend you to use an online database. If not, you can store the data to your iOS device using FMDatabase or simply SQLite
I have used DIFFBOT for web crawling in iOS. The site gives API for different purposes like product, analysing pages or articles. It comes with a free trail of 14 days too. Here is the code for a product web crawling:
let url = "https://api.diffbot.com/v3/product?token=YOURTOKEN&url=TheUrlWhichYouwantToSearchinURLENCODEDFORMAT"
let requestUrl = RequestHandlerToken(url: url, withPostMethod: false)
requestUrl.startRequest { (response, error) in
print(response)
self.parseData(resp: response)
}
The response will be coming in JSON format. Make sure that the URL is in URLencoded format. Here I am using custom class for hitting the request. You can do this by using nsurl session or connection.

iOS: using Yahoo's BOSS search API to receive web results for my iPhone app. OAuth errors

I've searched up and down for a solution, but each one I found do not work and Yahoo's BOSS documentation is awful. It shows you how to send a request to the API but it clearly lacks all of the other required parameters that need to be included to fulfill OAuth.
My app is a search app. I'm using a TableViewController and UISearchBar to populate the table with web search results.
My table cells work fine and the table populates with fake results.
[Image unavailable because I need 10 reputation points... wow.]
However, BOSS integration is proving to be a headache and I'm unfamiliar with this type of web programming.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSString *appid = #"{CONSUMER_KEY}"; // Provided by Yahoo
NSString *query = searchText;
NSString *address = #"http://boss.yahooapis.com/ysearch/web/v1/";
NSString *request = [NSString stringWithFormat:#"%#%#%#%#%#",address, query, #"?appid=", appid, #"&format=xml"];
// TEST URL: http://boss.yahooapis.com/ysearch/web/v1/gfdgfd?appid={CONSUMER_KEY}&format=xml
NSURL *URL = [NSURL URLWithString:request];
NSError *error;
NSString *XML = [NSString stringWithContentsOfURL:URL encoding:NSASCIIStringEncoding error:&error];
NSLog(#"%#", error);
{CONSUMER_KEY} is the long special key provided by Yahoo upon registering your app to use their service.
I was receiving all kinds of oauth errors but documentation online says that BOSS doesn't use OAuth.
If anyone knows how to set me in the right direction, that'd be fantastic. Thank you!

How to call xml-rpc webservice using objective c

Suppose, the webservice provider's server exposing the webservice in the form http://example.com:8000/api
What is best framework or library to access the webservice in ios 7 project
There are a few marshaling frameworks that support generating an object-graph from XML, however I would simply go for the following:
Invoke the service endpoint. My favorite library is BBHTTP, however you could use AFNetworking, NSURLConnection with gcd or whatever you prefer for asynch network calls.
Extract the relevant contents of the XML payload onto your use-case specific payload object using RaptureXML
I recommend having use-case specific payload objects because they model exactly what is needed for a given service invocation - supporting the notion of contract-first development. This allows you to change you internal model without effecting the integration to external systems. Similarly the external API can change without effecting your model.
You can create a category method on RXMLElement to return the element mapped to a use-case-specific object. A typical mapping usually takes just a handful of lines of code to marshal from wire-format to your payload object for the service invocation.
Here's an example (the code that I took it from wanted the payload wrapped in a SOAP envelope - just ignore that bit).
- (void)request:(MyUseCaseRequstPayload*)request onComplete:(void (^)(MyResponsePayload*))onSuccess
onError:(void (^)(NSError*))onError;
{
//Even more XML! You can stick your payload inside an envelope if you want
SoapEnvelope* envelope = [SoapEnvelope envelopeWithContent:[request xmlString]];
[[BBHTTPRequest postToURL:_serviceUrl data:[envelope data] contentType:#"text/xml"] execute:^(BBHTTPResponse* response)
{
RXMLElement* element = [RXMLElement elementFromXMLData:[response content]];
MyResponsePayload* response = [[element child:#"elementToBeMapped"] asMyObjectType];
if (onSuccess)
{
onSuccess(response);
}
} error:^(NSError* error)
{
LogDebug(#"Got error: %#", error);
if (onError)
{
onError(error);
}
}];
}

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.

Resources