How to give two json request to two different api at a time from one page and from one method - xcode

I am working on my new iPhone application,in that I need the datas and addresses from one url and from anther url I need to get the images. These two results are in the form of json response data but I am getting only the result for the datas....
Here is my code
- (void)viewDidLoad
{
jsondataimg=[[NSMutableString alloc] initWithString:#""];
#####for this url i'm not getting the result##########
NSString *urlimg = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",name];
//NSLog(#"%#",urlimg);
NSURL *url1= [NSURL URLWithString:urlimg];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL: url1];
NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
jsonData = [[NSMutableString alloc] initWithString:#""];
NSString *urlString = [NSString stringWithFormat: #"https://maps.googleapis.com/maps/api/place/details/json?reference=%#&sensor=false&key=your key",selectedname];
NSLog(#" the name is%#",selectedname);
NSLog(#" the reference is%#",selectedrefer);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
[connection1 release];
[request1 release];
[super viewDidLoad];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *partialData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *partialData1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[jsondataimg appendString:partialData1];
[jsonData appendString:partialData];
[partialData release];
[partialData1 release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
# pragma mark for fetching the image urls
NSDictionary *imageurls=[jsondataimg JSONValue];
NSDictionary*images=[imageurls objectForKey:#"responseData"];
NSLog(#"%#",images);
##########here null value is displaying#######
#pragma mark for fetching the datassss
NSDictionary *filesJSON = [jsonData JSONValue];
NSDictionary *address1 = [filesJSON valueForKey:#"result"];
NSLog(#"Found %#",address1);
}

Just use this no need to set delegate methods nsurl connections.. you will get the data...and same for next one.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=mumbai"]]];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// NSLog(#"%#",strResponse);
SBJSON *sbJason = [[SBJSON alloc] init];
NSMutableDictionary *getPlaceList = [sbJason objectWithString:strResponse];

Related

Storing JSON response in iOS error

I am making a call to an online php from my iOS app. In my output window I see the JSON Response with the data. But I need to store the NSString in my userdefaults but it is coming up NULL.
In this code the NSLog(#"JSON Response is %#", responseData); returns the json data just fine and I see the ipixid. But in the NSLog (#"ipixid is %#", ilixid); it returns ipixid is (null)
NSString *post =[[NSString alloc] initWithFormat:#"email=%#", strValue];
NSLog(#"PostData: %#",post);
NSURL *url1=[NSURL URLWithString:#"http://www.ipixsocial.com/membership/getresult.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Response is %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSString *username = [(NSString *) [jsonData objectForKey:#"email"]init];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"uid"] integerValue];
NSString* ipixid = [jsonData objectForKey:#"ipixid"];
[[NSUserDefaults standardUserDefaults] setObject:ipixid forKey:#"ipixid"];
NSLog (#"ipixid is %#", ipixid);
Don't ignore the "error" parameter you're passing to the parser. Also check that "jsonData" is not nil. I'm think that parsing is failing and because you're ignoring it and assuming jsonData is valid you're getting nil for [jsonData objectForKey:#"ipixid"];

Crash Occurring on First Launch When populating core data database

I keep getting an error in the debugger for my application saying,
2013-06-23 16:07:15.826 collection view recipies[5681:c07] -[NSManagedObject length]: unrecognized selector sent to instance 0x9495280
2013-06-23 16:07:15.827 collection view recipies[5681:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject length]: unrecognized selector sent to instance 0x9495280'
* First throw call stack:
(0x26ac012 0x1517e7e 0x27374bd 0x269bbbc 0x269b94e 0x2b11c4 0x16d80a 0x4464 0x64f2da 0x6508f4 0x652b91 0x19c2dd 0x152b6b0 0x18eefc0 0x18e333c 0x18eeeaf 0x23b2bd 0x183b56 0x18266f 0x182589 0x1817e4 0x18161e 0x1823d9 0x1852d2 0x22f99c 0x17c574 0x17c76f 0x17c905 0x185917 0x14996c 0x14a94b 0x15bcb5 0x15cbeb 0x14e698 0x2c06df9 0x2c06ad0 0x2621bf5 0x2621962 0x2652bb6 0x2651f44 0x2651e1b 0x14a17a 0x14bffc 0x1e9d 0x1dc5)
libc++abi.dylib: terminate called throwing an exception
In My application delegate, if check to see if the application is being launched for the first time, and if it is, I then add several image paths to the core data structure.
In AppDelegate.m under ApplicationDidFinishLaunchingWithOptions,
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"HasLaunchedOnce"])
{
// app already launched
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
// This is the first launch ever
NSArray *mainDishImages = [NSArray arrayWithObjects:#"egg_benedict.jpg", #"full_breakfast.jpg", #"ham_and_cheese_panini.jpg", #"ham_and_egg_sandwich.jpg", #"hamburger.jpg", #"instant_noodle_with_egg.jpg", #"japanese_noodle_with_pork.jpg", #"mushroom_risotto.jpg", #"noodle_with_bbq_pork.jpg", #"thai_shrimp_cake.jpg", #"vegetable_curry.jpg", nil];
NSArray *drinkDessertImages = [NSArray arrayWithObjects:#"angry_birds_cake.jpg", #"creme_brelee.jpg", #"green_tea.jpg", #"starbucks_coffee.jpg", #"white_chocolate_donut.jpg", nil];
for (NSString *imagePath in mainDishImages) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:#"Recipe" inManagedObjectContext:context];
[newRecipe setValue:imagePath forKey:#"imageFilePath"];
}
for (NSString *imagePath in drinkDessertImages) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:#"Deserts" inManagedObjectContext:context];
[newRecipe setValue:imagePath forKey:#"imageFilePath"];
}
}
And I access that data in my collectionViewController, I access that data.
- (NSManagedObjectContext *)managedObjectContext{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Deserts"];
deserts = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSFetchRequest *fetchRequestTwo = [[NSFetchRequest alloc] initWithEntityName:#"Recipe"];
meals = [[managedObjectContext executeFetchRequest:fetchRequestTwo error:nil] mutableCopy];
recipeImages = [NSArray arrayWithObjects:meals, deserts, nil];
[self.collectionView reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Deserts"];
deserts = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSFetchRequest *fetchRequestTwo = [[NSFetchRequest alloc] initWithEntityName:#"Recipe"];
meals = [[managedObjectContext executeFetchRequest:fetchRequestTwo error:nil] mutableCopy];
recipeImages = [NSArray arrayWithObjects:meals, deserts, nil];
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0);
self.navigationController.navigationBar.translucent = YES;
self.collectionView.contentInset = (UIEdgeInsetsMake(44, 0, 0, 0));
selectedRecipes = [NSMutableArray array];
}
According to crashalytics, the error is in the line where it says
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
In the method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame"]];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame-selected.png"]];
return cell;
}
I hope you can help. Thanks In Advance!
The UIImage method imageNamed takes an NSString as argument, but you pass a NSManagedObject to it.
You should get the image path from the managed object first. Try this:
id managedObject = [recipeImages[indexPath.section] objectAtIndex:indexPath.row];
NSString* imagePath = [managedObject valueForKey:#"imageFilePath"];
recipeImageView.image = [UIImage imageNamed:imagePath];

How to save and load a picture in Xcode

Check my app if you don't really understand ( Quick Notes!) But here it goes. My app is a notes app so it allows the user to select from few different kinds of note colors and designs below. When the user selects one, it changes the note above to what ever they set it to. So i need a button that will save the picture they selected, and when the leave the view and come back they can click the load button and the same image they selected will appear. I am using Xcode 4.3.
NSImageView is what your looking for.
This contains info on saving the file (look at the answer with code): Implement drag from NSImageView and save image to a file
The Code:
-(IBAction)saveImageButtonPushed:(id)sender
{
NSBitmapImageRep *rep;
NSData *data;
NSImage *image;
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
[self unlockFocus];
image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
[image addRepresentation:rep];
data = [rep representationUsingType: NSPNGFileType properties: nil];
//save as png but failed
[data writeToFile: #"asd.png" atomically: NO];
//save as pdf, succeeded but with flaw
data = [self dataWithPDFInsideRect:[self frame]];
[data writeToFile:#"asd.pdf" atomically:YES];
}
//......
#end
To load an image:
The Code:
NSImage loadedImage = [[NSImage alloc] initWithContentsOfFile: NSString* filePath]
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSDate *date = [[NSDate date] dateByAddingTimeInterval:1];
profile_img = [NSString stringWithFormat:#"%#.png",[dateFormatter stringFromDate:date]];
[profile_img retain];
NSLog(#"formattedDateString: %#",profile_img);
NSData *imageToUpload = UIImagePNGRepresentation(Img_View.image);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:ServerPath]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"Upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:profile_img mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject)
{
NSString *response = [operation2 responseString];
NSLog(#"response: [%#]",response);
NSString *post = [NSString stringWithFormat:#"Images=%#",profile_img];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [post length]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Gallery.php",ServerPath]];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"POST"];
NSLog(#"%#", post);
[request1 setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request1 setHTTPBody:postData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSString *responseString = [[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding] autorelease];
responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",responseString);
if([responseString isEqualToString:#"Entered data successfully"])
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Image Share" message:#"Image Share SuccessFully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[Alert show];
[Alert release];
}
else
{
}
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
NSLog(#"error: %#", [operation2 error]);
}];
[operation2 start];

Can i use NSTimer in background?

I use
NSString *urlStr=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Delay is %#",result);
timer = [NSTimer scheduledTimerWithTimeInterval:(5)
target:self
selector:#selector(loginunlogin:)
userInfo:nil
repeats:YES];
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
}
-(void) loginunlogin:(NSTimer *)theTimer{
NSString *urlStr=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Delay is %#",result);
delay=[result floatValue];
if([result isEqual:#"false"]==TRUE){
NSLog(#"Delay %#",result);
}else{
NSLog(#"User logged delay is %#",result);
[timer invalidate];
timer=nil;
delay=[result floatValue];
NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval: delay target:self selector:#selector(targetMethod:)
userInfo:nil repeats:YES];
}
}
-(void) targetMethod: (NSTimer*)theTimer {
mapView =[[MKMapView alloc] init];
mapView.showsUserLocation=YES;
float mylo =mapView.userLocation.coordinate.longitude;
float myla =mapView.userLocation.coordinate.latitude;
NSString *str1 =[[NSString alloc] initWithFormat:#"%f",mylo];
NSString *str2 =[[NSString alloc] initWithFormat:#"%f",myla];
NSLog(#"longi %#",str1);
NSLog(#"latit %#",str2);
NSString *req=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/messages/getnewmessagescount?longitude=%#&latitude=%#",str1,str2];
NSURL *url = [NSURL URLWithString:req];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",request);
if ([result isEqual: #"0"])
{
NSLog(#"No messages");
}else{
if ([result isEqual:#"false"]) {
NSLog(#"Not logged");
}else{
NSString *path = [NSString stringWithFormat:#"%#%#",
[[NSBundle mainBundle] resourcePath],
#"/tada.wav"];
//declare a system sound id
SystemSoundID soundID;
//Get a URL for the sound file
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
//Use audio sevices to create the sound
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
//Use audio services to play the sound
AudioServicesPlaySystemSound(soundID);
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *Date = [NSData date];
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:Date];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:Date];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [[NSString alloc] initWithFormat:#"Your have got (%#) new messages",result];
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"someValue" forKey:#"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release]; NSLog(#"bla %#",result);
}}
}
How to change code that it works in background
I am using this code to play the sound when my application enter into background you can customize it for your own use
- (void)applicationDidEnterBackground:(UIApplication *)application{
backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[NSThread sleepForTimeInterval:3];
[self startPlayingInBackground:#"default.aif"];
NSLog(#"Time remaining: %f",[application backgroundTimeRemaining]);
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
// if you don't call endBackgroundTask, the OS will exit your app.
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
});
}
The line below is the code with help of which m playing the sound it's my objective c function all
[self startPlayingInBackground:#"default.aif"];

how to text from url with xcode to a string

NSURL *url;
NSData *data;
NSString *blork;
url = [NSURL URLWithString: #"http://www.mycompanyaddress.com/identity_check.jsp?cliId=A-00000&security_key=00000"];
data = [url resourceDataUsingCache: NO];
blork = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
UIAlertView *testMessage = [[UIAlertView alloc] initWithTitle: #"From Server: " message: blork delegate: self cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[testMessage show];
[testMessage release];
RESOURCEDATAUSINGCACHE is now a deprecated function..otherwise it worked like a charm
you can use -
NSData *data = [NSData dataWithContentsOfURL:url];
and as document says
Use NSURLConnection instead of this method.

Resources