I want to send as an object as json
HTTP Headers: {
"Content-Length" = 24;
"Content-Type" = "application/json";
}
HTTP Body: {"userId":"5","mode":""}.
and get back a json
HTTP Headers: {
"Content-Type" = "application/json";
}
HTTP Body: {"insertCount":4,"offerCount":0,"favoriteOfferCount":0,"favoriteInsertCount":0}
and map it to an object, can anyone guide me as i'm getting many errors involving routers,object loader etc
I understand that i have to use RKObjectManager's postObject:mapResponseWith:delegate:
but configuring it is confusing.
never mind here's how i did it
#interface RestKitUtil : NSObject <RKObjectLoaderDelegate,RKRequestDelegate>
-(void)postobj;
#end
#implementation RestKitUtil
-(void)postobj{
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
[RKObjectManager objectManagerWithBaseURL:#"http://10.6.10.121:80/CW_war"];
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[CountResultVO class]];
[mapping mapKeyPathsToAttributes:
#"offercount", #"offercount",
#"insertCount", #"insertCount",
#"favouriteOfferCount", #"favouriteOfferCount",
#"favouriteInsertCount", #"favouriteInsertCount",
nil];
RKObjectRouter *router = [RKObjectManager sharedManager].router;
[router routeClass:[BasicUserArgVo class] toResourcePath:#"/getMyOffersCount" forMethod:RKRequestMethodPOST];
[RKObjectManager sharedManager].objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:#"objStore.sqlite"];
RKObjectMapping *listMapping = [RKObjectMapping mappingForClass:[BasicUserArgVo class]];
[listMapping mapKeyPath:#"userId" toAttribute:#"userId"];
[listMapping mapKeyPath:#"mode" toAttribute:#"mode"];
[[RKObjectManager sharedManager].mappingProvider addObjectMapping:listMapping ];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[listMapping inverseMapping] forClass:[BasicUserArgVo class]];
[[RKObjectManager sharedManager] setSerializationMIMEType:RKMIMETypeJSON];
//NSUTF8StringEncoding
[[RKObjectManager sharedManager] setAcceptMIMEType:RKMIMETypeJSON];
BasicUserArgVo *bvo = [[BasicUserArgVo alloc] initWithUserId:5];
[[RKObjectManager sharedManager] postObject:bvo mapResponseWith:mapping delegate:self];
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
CountResultVO* cvo = [objects objectAtIndex:0];
NSLog(#"values:%ld,%ld,%ld,%ld",[cvo offercount],[cvo insertCount],
[cvo favouriteOfferCount],[cvo favouriteInsertCount] );
}
- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
NSString *msg = [NSString stringWithFormat:#"Error: %#", [error localizedDescription]];
NSLog(#"log : %#",msg);
}
#end
Related
I am trying to playback a streamed media (radio).
I have failed in the attempt and also I have received the error message: App Transport Security (ATS).
How I can play a streaming radio?
My first try:
NSURL *url = [NSURL URLWithString:#"http://ccma-radioa-int-abertis-live.hls.adaptive.level3.net/int/mp4:catradio/chunklist.m3u8"];
WKAudioFileAsset *fileAsset = [WKAudioFileAsset assetWithURL:url];
WKAudioFilePlayerItem *playerItem = [WKAudioFilePlayerItem playerItemWithAsset:fileAsset];
self.audioPlayer = [WKAudioFilePlayer playerWithPlayerItem:playerItem];
if (self.audioPlayer.status == WKAudioFilePlayerStatusReadyToPlay) {
[self.audioPlayer play];
}
My second try:
NSURL *url = [NSURL URLWithString:#"http://ccma-radioa-int-abertis-live.hls.adaptive.level3.net/int/mp4:catradio/chunklist.m3u8"];
NSDictionary *options = #{WKMediaPlayerControllerOptionsAutoplayKey:#YES};
[self presentMediaPlayerControllerWithURL:url
options:options
completion:^(BOOL didPlayToEnd, NSTimeInterval endTime, NSError * __nullable error) {
if (!didPlayToEnd) {
NSLog(#"The player did not play all the way to the end. The player only played until time - %.2f.", endTime);
}
if (error) {NSLog(#"There was an error with playback: %#.", error);}
}];
Does anyone know how to get it?
How to resolve this issue.
" (entity: EventDetails; id: 0x155ebe90 ; data: )".
I am using below piece of code to fetch events from my entity.
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] parentContext];
writerObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
temporaryContext.parentContext = managedObjectContext;
[temporaryContext performBlockAndWait:^{
if (temporaryContext == nil) {
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] parentContext];
writerObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSManagedObjectContext *temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
temporaryContext.parentContext = managedObjectContext;
}
NSError *error = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"EventDetails"];
NSArray *arr = [temporaryContext executeFetchRequest:request error:&error];
NSLog(#" %#", arr);
if (![temporaryContext save:&error]) {
NSLog(#"Error in getsize - error:%#",[error userInfo]);
}
[managedObjectContext performBlockAndWait:^{
NSError *error = nil;
if(![managedObjectContext save:&error])
{
NSLog(#"error");
}
[writerObjectContext performBlockAndWait:^{
NSError *error = nil;
if(![writerObjectContext save:&error])
{
NSLog(#"error");
}
}]; // writer
}]; // main
}]; // parent
I runned above code both on my iphone and simulator.But getting same result. How to get rid of this?
data: <fault> (presumably from a log statement) simply means that Core Data did not fetch all the associated data from the database but will make future trips to the store automatically, should the information be needed.
In other words, this is normal behavior. You do not need to worry about it.
In this app, I am using an sqlite database that was created by another app. I can query the database using the Firefox SQLite Manager and see that what I am searching for does exist in the database. I have reduced my query to something very simple, but still get nothing returned in my NSFetchedResultsController.
Here is my code:
- (NSFetchedResultsController*) frc {
if (!frc_) {
#autoreleasepool {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription * entity = [NSEntityDescription entityForName:#"INDEX" inManagedObjectContext:[ManagedObjectContext moc]];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:15];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"lemma = 'dog'"];
[NSFetchedResultsController deleteCacheWithName:nil];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:#"lemma" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController =
[[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:[ManagedObjectContext moc]
sectionNameKeyPath:#"lemma"
cacheName:nil];
aFetchedResultsController.delegate = (id<NSFetchedResultsControllerDelegate>)self;
NSError *error = nil;
if (![aFetchedResultsController performFetch:&error]) {
NSLog(#"Unresolved Error %#, %#", error, [error userInfo]);
abort();
}
self.frc = aFetchedResultsController;
}
}
return frc_;
}
There is an entity called "INDEX" in the data model. To confirm that the entity has the lemma property, I show the content of its lemma property, getting this:
po [[entity propertiesByName] objectForKey:#"lemma"]
(id) $3 = 0x1104f740 (<NSAttributeDescription: 0x1104f740>), name lemma, isOptional 1, isTransient 0, entity INDEX, renamingIdentifier lemma, validation predicates (
), warnings (
), versionHashModifier (null)
userInfo {
}, attributeType 700 , attributeValueClassName NSString, defaultValue (null)
Examining the contents of the aFetchedResultsController immediately after the fetch (where it is assigned to self.frc) gives this:
po aFetchedResultsController
(NSFetchedResultsController *) $4 = 0x1105c5c0 <NSFetchedResultsController: 0x1105c5c0>
po [[aFetchedResultsController fetchedObjects] count]
(id) $1 = 0x00000000 <nil>
I suppose the problem here is something very basic, but I don't know what I am overlooking.
I found the answer at the Ray Wenderlich site. The problem is that the sqlite file must be moved from the application bundle to the application documents directory.
This is done by copying it form the bundle into the documents directory if it is not already there.
Here is the code for creating the persistent store coordinator:
- (NSPersistentStoreCoordinator *)pstore {
if (pstore_ != nil) {
return pstore_;
}
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"words.sqlite"];
NSURL *storeUrl = [NSURL fileURLWithPath: storePath];
// THIS IS THE KEY PIECE TO IMPORTING AN EXISTING SQLITE FILE:
// Put down default db if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
NSString *defaultStorePath = [[NSBundle mainBundle]
pathForResource:#"words" ofType:#"sqlite"];
if (defaultStorePath) {
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
}
}
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSError *error = nil;
pstore_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.mom];
if(![pstore_ addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:options error:&error]) {
// Error for store creation should be handled in here
}
return pstore_;
}
I m pretty much new to objective-C and strucked at a point.I have to POST XML request to rest service url and get the response from it .I m using NSMutableRequest.But couldn't see any response.Couldn't understand where I m going wrong ...
Request XML is like this:
<GetUserRequest xmlns="http://schemas.datacontract.org/2004/07/DModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ID>456789</ID>
<UserEmail>John#yahoo.com</UserEmail>
</GetUserRequest>
My url is like this : http://192.158.0.104:8732/IServices/GetXml
MY code goes like this :
NSString *urlString1=[NSString stringWithFormat:#"http://192.158.0.104:8732/IServices/GetXml"];
NSMutableURLRequest *request=[[[NSMutableURLRequest alloc] init]autorelease];
[request setURL:[NSURL URLWithString:urlString1]];
[request setHTTPMethod:#"POST"];
NSString *contentType=[NSString stringWithFormat:#"application/xml"];
[request addValue:contentType forHTTPHeaderField:#"Content-type"];
NSMutableData *postBody=[NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"<GetUserRequest xmlns=\"http://schemas.datacontract.org/2004/07/DModel\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"]dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<ID>456789</ID>"]dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<UserEmail>John#yahoo.com</UserEmail>"]dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"/GetUserRequest>"]dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSHTTPURLResponse *urlResponse=nil;
NSError *error=[[NSError alloc]init];
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *rss=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding ];
NSlog(#"Response Code:%d",[urlResponse statusCode]);
if([urlResponse statusCode ]>=200 && [urlResponse statusCode]<300)
{
NSLog(#"Response:%#",rss);
}
But I couldnot see anything in active console...
Any help would be appreciated ...
That code looks poor to me and doesn't contain enough error checking ([NSURLConnection sendSynchronousRequest] can return nil when an error occurs). Modify the end to:
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
if (responseData != nil)
{
NSString *rss = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding ];
NSlog(#"Response Code:%d",[urlResponse statusCode]);
if([urlResponse statusCode ]>=200 && [urlResponse statusCode]<300)
{
NSLog(#"Response:%#",rss);
}
}
else
{
NSLog(#"Failed to send request: %#", [error localizedDescription]);
}
I am trying to log into google reader using AfNetworking AfHttpClient but I am getting this error that I can;t seem to figure out.
Below is my subclass of AFNetworking:
// main url endpoints
#define GOOGLE_ACCOUNTS_BASE_URL #"https://www.google.com/accounts/"
#implementation ADPGoogleLoginClient
+ (ADPGoogleLoginClient *)sharedClient {
static ADPGoogleLoginClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[ADPGoogleLoginClient alloc] initWithBaseURL:[NSURL URLWithString:GOOGLE_ACCOUNTS_BASE_URL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFXMLRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Content-type" value:#"text/plain"];
[self setDefaultHeader:#"Accept" value:#"text/plain"];
return self;
}
#end
And then I try to form a request by using the following code:
//set up request params
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"googlereader-ios-client", #"client",
[keychainCredentials objectForKey:(__bridge id)kSecAttrAccount], #"Email",
[keychainCredentials objectForKey:(__bridge id)kSecValueData], #"Passwd",
#"reader", #"service",
#"ipad", #"source", nil];
//make requests
[[ADPGoogleLoginClient sharedClient] getPath:#"ClientLogin"
parameters:params
success:^(AFHTTPRequestOperation *operation , id responseObject)
{
//parse out token and store in keychain
NSString* responseString = [operation responseString];
NSString* authToken = [[[responseString componentsSeparatedByString:#"\n"] objectAtIndex:2]
stringByReplacingOccurrencesOfString:#"Auth=" withString:#""];
keychainToken = [[KeychainItemWrapper alloc] initWithIdentifier:#"GReaderToken" accessGroup:nil];
[keychainToken setObject:authToken forKey:(__bridge id)kSecValueData];
loginSuccess();
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"There was an error logging into Reader - %#", [error localizedDescription]);
loginFailure(error);
}];
Im setting the default headers to
[self setDefaultHeader:#"Content-type" value:#"text/plain"];
[self setDefaultHeader:#"Accept" value:#"text/plain"];
so im not sure why it still thinks it is expecting xml?
You are setting the Content-Type header for the request, but the error you're seeing is from the response. In order for requests to be considered "successful", the content type needs to match up with expectations (so as to avoid trying to parse a JSON response when you expected XML).
In that same error code, it should have mentioned what content type it actually got back. If it is indeed XML, add that using AFXMLRequestOperation +addAcceptableContentTypes:, and everything should work just fine.
Hi Matt so I just got around to testing this. Looks like I was registering the wrong AF operation. I changed
[self registerHTTPOperationClass:[AFXMLRequestOperation class]];
to
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
and all was good!