Just want my JSON data using RestKit .20.3 without using a UITableView / NSFetchedResultsController - iphone

I have followed several tutorials that use the NSFetchedResultsController class to retrieve and display data to show in a UITableView. What if I simply want to display pieces of my JSON result set in a text box on a simple UIViewController? Does anyone have an example how to do this? Below is a snippet of my code;
// Request Object with json paramaters
RequestInquiry *requestInquiry = [[RequestInquiry alloc] init];
requestInquiry.docType = #"T";
//requestInquiry.documentNum = #"999999999";
requestInquiry.documentNum = self.strTicketNum;
requestInquiry.clientAccount = #"6";
requestInquiry.clientCode = #"02";
requestInquiry.token = #"f1234XFASF43434";
requestInquiry.requestType = #"submit";
requestInquiry.userId = #"XXXX";
requestInquiry.class1 = #"class com.rest.client.JsonRequest";
[[RKObjectManager sharedManager] postObject:requestInquiry path:#"/RestIVR/restservices/ticketservices/jinquiry" parameters:nil success:nil failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#",error);
}];

- (void)callRemoteServiceWithPath: (NSString *)path postObject: (id)object andParameters: (NSString *)params withBlock:(void (^)(id ))block {
RKObjectManager *manager = [[MFRestKit sharedDataManager] objectManager];
NSData *postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path relativeToURL:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
RKManagedObjectRequestOperation *operation = [manager managedObjectRequestOperationWithRequest:request managedObjectContext:manager.managedObjectStore.persistentStoreManagedObjectContext success:^(RKObjectRequestOperation *operation1, RKMappingResult *mappingResult) {
block ([mappingResult array]);
} failure:^(RKObjectRequestOperation *operation1, NSError *error) {
RKLogDebug(#"Failure %#",error.debugDescription);
block (error);
}];
[manager enqueueObjectRequestOperation:operation];
}

Related

How to wait response and parse XML done in afnetworking iOS

I want to wait until server reponse and parse XML done, then call another function. How can i do that? I used this code to send request to server and use NSXMLParser to parse XML response.
NSURL *url1 = [NSURL URLWithString:#"linkserver"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url1] ;
NSDictionary *params1 = #{
#"a" : vd;
#"b" : #"all"
};
NSMutableURLRequest *afRequest = [httpClient requestWithMethod:#"GET" path:nil parameters:params1] ;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
[self parseXMLFile:parsexmlinput];// parse xml
[self getItemFromStatus];// wait to call another function at here???
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
}
Please give me any suggestion. Thanks much
You have to make your request synchronous.
refer code something like:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friends/ids.json?"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
check this tutorial Ray Wenderlich using AFnetworking.
Using blocks and callbacks
- (IBAction)xmlTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:#"%#weather.php?format=xml",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
}];
[operation start];
}
You can do it in synchronous way...
NSURLResponse *response = nil;
NSError *error = nil;
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:[url path] parameters:params];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if(error) {
errorCallback(error, nil);
} else {
//parse the xml here
}
OR
You can achive it by adding [operation waitUntilFinished],after it's added to the operation queue.Refer this==>Can AFNetworking return data synchronously (inside a block)?
OR
EDIT: In case you don't want to use the AFNetworking library.I prefer this way.
NSString *action_Post =[[NSString alloc] initWithFormat:#"authToken=%#",theMutableString];
NSURL *action_Url =[NSURL URLWithString:#"ur url here"];
NSData *action_PostData = [action_Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *action_postLength = [NSString stringWithFormat:#"%d", [action_PostData length]];//your parameter to be posted here
NSMutableURLRequest *action_Request = [[NSMutableURLRequest alloc] init];
[action_Request setURL:action_Url];
[action_Request setHTTPMethod:#"POST"];
[action_Request setValue:action_postLength forHTTPHeaderField:#"Content-Length"];
[action_Request setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[action_Request setHTTPBody:action_PostData];
NSURLResponse *action_response;
NSData *action_Result = [NSURLConnection sendSynchronousRequest:action_Request returningResponse:&action_response error:&error];
if (!action_Result)
{
NSLog(#"Error");
}
else
{
//Parse your xml here
//call ur function
}
Modify it according to your GET/PUT methods.But i suggest you to go for POST method,as it is refered to be as secured one.

HTTP Post method php and ios

i'm facing a big problem,
I want to send data to my server, my data is a string.
I do not want to use Get method because the string might be very long, so i want to use POST method but everything goes, wrong, if someone can help me he'll be my hero :)
Here is my php code :
<?php include("config.inc.php");
if (isset($_POST['contentInterro']) && $_POST['contentInterro'] !="" ) {
//$id_user = $_POST['contentInterro'];
//$db->sql_query("INSERT INTO interrogations VALUES(DEFAULT, '$id_user')");
echo "succes";
}else{
echo "This is an error";
}
?>
Here is my app code :
NSData *postData = [stringToPost2 dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *requestPost = [[NSMutableURLRequest alloc] init];
NSURL *urlPost = [NSURL URLWithString:#"http://buzznapps.fr/FDF/postInterrogation.php"];
[requestPost setURL:urlPost];
[requestPost setHTTPMethod:#"POST"];
[requestPost setValue:#"lol" forHTTPHeaderField:#"contentInterro"];
NSError *errorURL;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:requestPost returningResponse:&response error:&errorURL];
NSString *str = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Str = %#",str);
I always get an error, and i've search the web i do not know how to get this data !
Thanks for any help.
#define TIMEOUT_INTERVAL 60
#define CONTENT_TYPE #"Content-Type"
#define URL_ENCODED #"application/x-www-form-urlencoded"
#define GET #"GET"
#define POST #"POST"
-(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:GET];
return req;
}
-(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:POST];
[req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
[req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
#try
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *_postData = [NSString stringWithFormat:#"user_name=%#&password=%#",#"user_name",#"password"];
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error==%#==",[error localizedDescription]);
}
else
{
NSError *errorInJsonParsing;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];
if(errorInJsonParsing) //error parsing in json
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error in json==%#==",[error localizedDescription]);
}
else
{
//do some operations
}
}
}];
}
#catch(NSException *exception)
{
NSLog(#"error in exception==%#==",[exception description]);
}
same way it works for the get method, just call the
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingGetMethodWithUrl:_url]; instead of NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];

How to post an array value in JSON

I want to post an array value in JSON.
Below is my code :
-(void)getConnection {
NSArray *comment=[NSArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSURL *aurl=[NSURL URLWithString:#"http://sajalaya.com/taskblazer/staffend/form/iphonearraytest.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:aurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
// NSString *new = [comment JSONString];
// NSArray *new=[comment jsonvalue];
NSString *postString=[NSString stringWithFormat:#"tag=&comment=%#&total=%#",new,#"4"];
NSLog(#"this is post string%#",postString);
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
We don't know your question, but my answer is short and simple. You should use great open source library for this, which is: AFNetworking, and do request like this:
_httpClient = [[AFHTTPClient alloc] initWithBaseURL:[[NSURL alloc] initWithString:#"http://sajalaya.com"]];
[_httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
new, #"comment",
#4, #"total,
nil];
NSMutableURLRequest *request = [self.httpClient requestWithMethod:#"POST"
path:#"/taskblazer/staffend/form/iphonearraytest.php"
parameters:params];
request.timeoutInterval = 8;
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
}];
Please use the following Mutable Array Operation componentsJoinedByString.
e.g.
NSMutableArray *commennts=[NSMutableArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSString* strCommentsJoin = [commennts componentsJoinedByString:#","]; // Please use your separator

NSURLRequest : Post data and read the posted page

In iOS (current target 5.0, Base SDK 5.1) how can I send a post request to a server, and then read the contents of the page. For example, the page takes a username and password, and then echos true or false. This is just for a better understanding of NSURLRequest.
Thanks in Advance!
A few things first
Decide how you want to encode your data - JSON or url-encoding are a good start.
Decide upon a return value - will it be 1, TRUE or 0, FALSE, or even YES/non-nil nothing/nil.
Read up on the URL Loading System, it's your friend.
Aim to make all your url connections asynchronous so your UI remains responsive. You can do this with NSURLConnectionDelegate callbacks. NSURLConnection has a small drawback: your code must be decoupled. Any variables you want available in the delegate functions will need to be saved to ivars or in your request's userInfo dict.
Alternatively you can use GCD, which, when coupled with the __block qualifiers, allows you to specify error/return code at the point you declare it - useful for one off fetches.
Without further ado, here's a quick and dirty url-encoder:
- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {
NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *part = [NSString stringWithFormat: #"%#=%#", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:#"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}
Using a JSON library like JSONKit makes encoding things easier, consider it!
Method 1 - NSURLConnectionDelegate async callbacks:
// .h
#interface ViewController : UIViewController<NSURLConnectionDelegate>
#end
// .m
#interface ViewController () {
NSMutableData *receivedData_;
}
#end
...
- (IBAction)asyncButtonPushed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://localhost/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:#"user", #"username",
#"password", #"password", nil];
NSData *postData = [self encodeDictionary:postDict];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData_ setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData_ appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data", [receivedData_ length]);
NSString *responeString = [[NSString alloc] initWithData:receivedData_
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:#"true"]) {
// Deal with true
return;
}
// Deal with an error
}
Method 2 - Grand Central Dispatch async function:
// .m
- (IBAction)dispatchButtonPushed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://www.apple.com/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:#"user", #"username",
#"password", #"password", nil];
NSData *postData = [self encodeDictionary:postDict];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Peform the request
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error) {
// Deal with your error
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"HTTP Error: %d %#", httpResponse.statusCode, error);
return;
}
NSLog(#"Error %#", error);
return;
}
NSString *responeString = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:#"true"]) {
// Deal with true
return;
}
// Deal with an error
// When dealing with UI updates, they must be run on the main queue, ie:
// dispatch_async(dispatch_get_main_queue(), ^(void){
//
// });
});
}
Method 3 - Use an NSURLConnection convenience function
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Hope this helps.
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
NSError *err = nil;
NSHTTPURLResponse *res = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
if (err)
{
//handle error
}
else
{
//handle response and returning data
}
This project might be quite handy for your purpose. It will take care of your downloads and store it locally. Check out the link https://github.com/amitgowda/AGInternetHandler

How to send a Get request in iOS?

I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as
[requestObject setHTTPMethod:#"GET"];
Tell me what could be the problem. Also provide me the code if you have.
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Make sure your requestObject is of type NSMutableURLRequest.
Simply call and use:
(void)jsonFetch{
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSError *erro = nil;
if (data!=nil) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];
if (json.count > 0) {
for(int i = 0; i<10 ; i++){
[arr addObject:[[[json[#"feed"][#"entry"] objectAtIndex:i]valueForKeyPath:#"im:image"] objectAtIndex:0][#"label"]];
}
}
}
dispatch_sync(dispatch_get_main_queue(),^{
[table reloadData];
});
}];
[data resume];
}