Loading images from parse to image views - iphone

I want to load images from parse as you can see in the screenshot.
i am using this code to load the header image into my imageview.
PFQuery *query = [PFQuery queryWithClassName:#"AppOfTheDay"];
[query getObjectInBackgroundWithId:#"WDJpxs4PzH"
block:^(PFObject *retreive, NSError *error) {
{
NSString *text = [retreive objectForKey:#"description"];
if (error) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
UIAlertView *error=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Connection Failed" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[error show];
}
else{
PFFile *imageFile = [retreive objectForKey:#"header"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (error) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
UIAlertView *error=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Something went wrong" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[error show];
}
else{
UIImage *image = [UIImage imageWithData:data];
_headerImage.image=image;
_appDescription.text=text;
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
}];
}
}
}];
My question is how can i similarly load my other three images into imageviews?

implement lazy loading images.
for example-NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
if ( queue == nil )
{
queue = [[NSOperationQueue alloc] init];
}
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * resp, NSData *data, NSError *error)
{
dispatch_async(dispatch_get_main_queue(),^
{
if ( error == nil && data )
{
UIImage *urlImage = [[UIImage alloc] initWithData:data];
thumbnail.image = urlImage;
}
});
}];

I hope it will help you alot,It will sort your problem with best loading speed
//yourclass.h
AsyncImageView *imageasy,*imageasy1, *imageasy2,imageasy3;
yourclass.m
PFQuery *query = [PFQuery queryWithClassName:#"AppOfTheDay"];
[query getObjectInBackgroundWithId:#"WDJpxs4PzH"
block:^(PFObject *comment, NSError *error) {
if (!error) {
PFFile *post = [comment objectForKey:#"PhotoName"];
PFFile *post2 = [comment objectForKey:#"logo"];
PFFile *post3 = [comment objectForKey:#"similar1"];
PFFile *post4 = [comment objectForKey:#"similar2"];
imageasy=[[AsyncImageView alloc] init];
imageasy1=[[AsyncImageView alloc] init];
imageasy2=[[AsyncImageView alloc] init];
imageasy3=[[AsyncImageView alloc] init];
[imageasy setImageURL:[NSURL URLWithString:[post url]]];
[imageasy1 setImageURL:[NSURL URLWithString:[post2 url]]];
[imageasy2 setImageURL:[NSURL URLWithString:[post3 url]]];
[imageasy3 setImageURL:[NSURL URLWithString:[post4 url]]];
}];

Related

What is the correct way to write the video in asset library and then get their attributes

I am writing video in Asset library using
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error) block
gives the url before the video completely write to the asset library. And when i enumerate the library inside the block to get the attributes of video i did not get any video against the url given by above block.
If i manually re-enumerate the asset library 3 or 4 times with the same url i get the video attribures.
This problem mostly occurs when i make video of duration greater than 5 min
My code is:
library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error)
{
savedAssetURL = assetURL;
[self assetsEmumeration:assetURL];
NSLog(#"asset url %#",assetURL);
if(error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Failed" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alertView show];
}
}];
-(void) assetsEmumeration:(NSURL *)_url
{
NSLog(#"assets enumeration ");
ALAssetsLibrary *al;
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]] ;
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSURL *url = [representation url];
if([[url absoluteString] isEqualToString:[_url absoluteString]])
{
found = TRUE;
NSDictionary *asset_options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:asset_options];
Float64 dur = CMTimeGetSeconds(avAsset.duration);
NSString *fileName = [representation filename];
appDelegate.videoLength = [NSString stringWithFormat:#"%f seconds",dur];
appDelegate.videoSize = [NSString stringWithFormat:#"%lld bytes",[representation size]];
appDelegate.originalFileName = [NSString stringWithFormat:#"%#",fileName];
[MBProgressHUD hideHUDForView:self.view animated:YES];
ExtraInfoViewController *extraInfoViewObj = [[ExtraInfoViewController alloc] init];
[self.navigationController pushViewController:extraInfoViewObj animated:YES];
NSLog(#"duration:%f,fileName:%#",dur,fileName);
}
else
{
found = FALSE;
}
}
}];
if(found == FALSE)
{
NSLog(#"video not found");
}
};
void (^assetFailureBlock)(NSError *) = ^(NSError *error)
{
NSLog(#"failure");
if(ALAssetsLibraryAccessGloballyDeniedError)
{
UIAlertView *alerview = [[UIAlertView alloc] initWithTitle:#"Denied" message:#"Failed to get the meta data. Access to assets library is denied" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alerview show];
}
};
al=[RecordVideoViewController defaultAssetsLibrary];
[al enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock:assetFailureBlock];
}
// find out alAsset for that url and then do whatever you want with alAsset.
library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error)
{
savedAssetURL = assetURL;
NSLog(#"asset url %#",assetURL);
if(error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Failed" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alertView show];
}
else
{
[library assetForURL:assetURL
resultBlock:^(ALAsset* alAsset) {
// do whatever you want with alAsset
}];
}
}];

SLRequest performRequestWithHandler does not work in ios 6

I am trying to build simple prototype where I post some text to my facebook account. I have read the ios 6 facebook integration documentation and came up with following code. Everything seems to work fine until I hit the last block where I create SLRequest object in method postTextToFacebook and try to execute performRequestWithHandler with handler block. Control never does inside the handler block. I am assuming that performRequestWithHandler call is not successful in this case. Any one have done with successfully? Here is code for your reference.
#import <Social/Social.h>
#import "ViewController.h"
#implementation ViewController
#synthesize facebookAccount;
#synthesize accountStore;
#synthesize textToPost;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction) postToFacebook:(id)sender
{
self.statusLabel.text = #"Logging in ...";
if(self.accountStore == nil)
{
self.accountStore = [[ACAccountStore alloc] init];
}
ACAccountType *facebookAccountType = [self.accountStore enter code hereaccountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSMutableDictionary *myOptions = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"172197712918906", ACFacebookAppIdKey,
[NSArray arrayWithObjects:#"email", #"user_about_me", #"user_likes", nil], ACFacebookPermissionsKey, ACFacebookAudienceFriends, ACFacebookAudienceKey, nil];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:myOptions completion:^(BOOL granted, NSError *error){
__block NSString *statusText;
if(granted)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookAccountType];
self.facebookAccount = [accounts lastObject];
[myOptions setObject:[NSArray arrayWithObjects:#"publish_stream", nil] forKey:ACFacebookPermissionsKey];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:myOptions completion:^(BOOL granted, NSError *error) {
__block NSString *statusText1;
if(granted && error == nil)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookAccountType];
self.facebookAccount = [accounts lastObject];
[self postTextToFacebook];
statusText1 = #"Text Posted.";
}
else{
statusText1 = #"Publish Failed.";
}
dispatch_async(dispatch_get_main_queue(), ^{
self.statusLabel.text = statusText1;
});
}];
}
else{
statusText = #"Login Failed.";
NSLog(#"Error = %#",error);
}
}];
}
-(void) postTextToFacebook
{
NSDictionary *parameters = #{#"message":self.textToPost.text};
NSURL *feedURL = [NSURL URLWithString:#"https://graphs.facebook.com/me/feed"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:feedURL parameters:parameters];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(#"Facebook request received, status code %d", urlResponse.statusCode);
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response data: %#", response);
//handle errors
if(error == nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
self.statusLabel.text = #"text posted to facebook";
});
}
}];
}
#end
Your url should be
https://graph.facebook.com/me/feed
instead of
https://graphs.facebook.com/me/feed
I was having a same issue and got an NSURLErrorDomain -1003 error on it.

How to get cookies and use them for other requests like POST ( iOS )?

My previous question was about the problem that I have to login each time for doing web services like posting a link or uploading a picture. Philipe answered that I have to use cookies instead of login process for each request. I found this method for getting cookies:
- (void)getCookies {
NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest *request;
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://MyWebsite.com/login.php"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:120];
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:#"http://MyWebsite.com/login.php"]];
NSLog(#"%d", all.count);
for (NSHTTPCookie *cookie in all) {
NSLog(#"Name: %# : Value: %#", cookie.name, cookie.value);
NSLog(#"Comment: %# : CommentURL: %#", cookie.comment, cookie.commentURL);
NSLog(#"Domain: %# : ExpiresDate: %#", cookie.domain, cookie.expiresDate);
NSLog(#"isHTTPOnly: %c : isSecure: %c", cookie.isHTTPOnly, cookie.isSecure);
NSLog(#"isSessionOnly: %c : path: %#", cookie.isSessionOnly, cookie.path);
NSLog(#"portList: %# : properties: %#", cookie.portList, cookie.properties);
NSLog(#"version: %u", cookie.version);
}
}
I also found this code to use these cookies, but I'm not sure how to use it:
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookies];
Here is my method for POSTing, I am using RestKit API:
- (IBAction)addLinkPressed:(UIButton *)sender {
[RKClient clientWithBaseURLString:#"http://MyWebsite.com"];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
self.linkField.text, #"url",
self.linkTitleField.text, #"title",
self.linkSummaryField.text, #"summary",
nil];
RKRequest *request = [[RKClient sharedClient] post:#"/send_link.php" params:params delegate:self];
[request setUserData:#"sendLink"];
}
Question: Which property of cookies should I store to use it for login information and where should I put it in my code?
I solved this issue by some inefficient way. Here is my methodology:
First I try to post to the web service and after posting I parse the returning HTML to see if the posting was successful or not. If posting was successful I give an appropriate message to the user that you post successfully but if it was not successful it could have two reasons: First: there were some error during the post execution Second: the user was not logged in. The way that I recognize the differentiation between fist and second error is just parsing the response HTML.
Here is the code that I used for this methodology (this is for the time that the user wants to change the password)
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {
NSRange range = [[error localizedDescription] rangeOfString:#"-1012"];
if (range.length > 0){
//First error occurs here
}
RKLogError(#"Hit error: %#", error);
}
- (IBAction)requestToChangePasswordPressed {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading";
[RKClient clientWithBaseURLString:#"http://WebServiceDomain.com"];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
self.oldPasswordField.text, #"oldPassword",
self.passwordNew.text, #"newPassword",
self.confirmPasswordField.text, #"confirmPassword",
nil];
RKRequest *request = [[RKClient sharedClient] post:#"/change_password.php" params:params delegate:self];
[request setUserData:#"changePassword"];
[self.view endEditing:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)autoLogin {
[RKClient clientWithBaseURLString:#"http://WebServiceDomain.com"];
[RKObjectManager sharedManager].client=[RKClient sharedClient];
RKParams *parameters = [RKParams params];
[parameters setValue:[[NSUserDefaults standardUserDefaults] objectForKey:#"defaultUsername"] forParam:#"username"];
[parameters setValue:[[NSUserDefaults standardUserDefaults] objectForKey:#"defaultPassword"] forParam:#"password"];
[[RKClient sharedClient] setAuthenticationType:RKRequestAuthenticationTypeHTTP];
// because we have two POSTs and we want to use the same method for both of the for didLoadResponse: we set the UserDate like bellow
RKRequest *request = [[RKClient sharedClient] post:#"/login.php" params:parameters delegate:self];
[request setUserData:#"login"];
}
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response
{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading";
id userData = [request userData];
if ([userData isEqual:#"login"]) {
if ([request isGET]) {
// Handling GET /foo.xml
if ([response isOK]) {
// Success! Let's take a look at the data
NSLog(#"Retrieved XML: %#", [response bodyAsString]);
}
} else if ([request isPOST]) {
// Handling POST /other.json
if ([response isJSON]) {
NSLog(#"Got a JSON response back from our POST!");
}
} else if ([request isDELETE]) {
// Handling DELETE /missing_resource.txt
if ([response isNotFound]) {
NSLog(#"The resource path '%#' was not found.", [request resourcePath]);
}
}
}
else if ([userData isEqual:#"sendLink"]) {
NSData *addLinksHtmlData = response.body;
// 2
TFHpple *addlinksParser = [TFHpple hppleWithHTMLData:addLinksHtmlData];
// 3
NSString *errorLinksXpathQueryString = #"//div[#class='errorBox']/ul/li";
NSArray *errorLinksNodes = [addlinksParser searchWithXPathQuery:errorLinksXpathQueryString];
// 4
NSMutableArray *newErrorLinks = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in errorLinksNodes) {
// 5
AllModels *errorTitle = [[AllModels alloc] init];
[newErrorLinks addObject:errorTitle];
// 6
errorTitle.errorTitle = [[element firstChild] content];
}
// 8
self.linkErrorObjects = newErrorLinks;
NSString *successLinksXpathQueryString = #"//div[#class='successBox']";
NSArray *successLinksNodes = [addlinksParser searchWithXPathQuery:successLinksXpathQueryString];
// 4
NSMutableArray *newSuccessLinks = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in successLinksNodes) {
// 5
AllModels *successTitle = [[AllModels alloc] init];
[newSuccessLinks addObject:successTitle];
// 6
successTitle.successTitle = [[element firstChild] content];
}
// 8
self.linkSuccessObjects = newSuccessLinks;
}
else {
NSLog(#"HTTP status code: %d", response.statusCode);
NSLog(#"HTTP status message: %#", [response localizedStatusCodeString]);
NSLog(#"Header fields: %#", response.allHeaderFields);
NSLog(#"Body: %#", response.bodyAsString);
NSData *HtmlData = response.body;
// 2
TFHpple *addParser = [TFHpple hppleWithHTMLData:HtmlData];
// 3
NSString *errorXpathQueryString = #"//div[#class='errorBox']/ul/li";
NSArray *errorNodes = [addParser searchWithXPathQuery:errorXpathQueryString];
// 4
NSMutableArray *newError = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in errorNodes) {
// 5
AllModels *errorTitle = [[AllModels alloc] init];
[newError addObject:errorTitle];
// 6
errorTitle.errorTitle = [[element firstChild] content];
}
// 8
self.ErrorObjects = newError;
NSString *successXpathQueryString = #"//div[#class='successBox']";
NSArray *successNodes = [addParser searchWithXPathQuery:successXpathQueryString];
// 4
NSMutableArray *newSuccess = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in successNodes) {
// 5
AllModels *successTitle = [[AllModels alloc] init];
[newSuccess addObject:successTitle];
// 6
successTitle.successTitle = [[element firstChild] content];
}
// 8
self.successObjects = newSuccess;
[self errorCheck];
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)errorCheck {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading";
if(self.errorObjects.count > 0) {
AllModels *errorlink = [self.errorObjects objectAtIndex:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"There is a problem" message:errorlink.errorTitle delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil , nil];
[alert show];
}
else {
if(self.linkErrorObjects.count > 0) {
[self autoLogin];
[self requestToChangePasswordPressed];
}
else {
AllModels *successlink = [self.successObjects objectAtIndex:0];
self.successLabel.hidden = NO;
self.successLabel.text = successlink.successTitle;
NSLog(#"Success Title: %#",successlink.successTitle);
[UIView animateWithDuration:3.0
delay:0.0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{ self.successLabel.alpha = 0.0; }
completion:^(BOOL fin) { if (fin) [self.successLabel removeFromSuperview]; }];
[self performSelector:#selector(dismissModalViewController) withObject:nil afterDelay:1.0];
}
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}

Recalling viewDidLoad after failed connection not working

this is my viewDidLoad function working well :
- (void)viewDidLoad
{
[super viewDidLoad];
//iAds code
adview = [[ADBannerView alloc] initWithFrame:CGRectZero];
adview.frame = CGRectOffset(adview.frame, 0, 0);
adview.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifierPortrait];
adview.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
[self.view addSubview:adview];
adview.delegate = self;
self.adbanerinvesiable = NO;
//php data code
NSError *er;
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8888/newjson.php?number=1"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (response.length != 0){
NSString *json_string = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
listt = [parser objectWithString:json_string error:&er];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"No Internet conniction" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:#"Refresh", nil];
[alert show];
//for ID contet post
SBJsonParser *parser2 = [[SBJsonParser alloc] init];
NSURLRequest *request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8888/newjson.php?number=2"]];
NSData *response2 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:nil error:nil];
NSString *json_string2 = [[NSString alloc]initWithData:response2 encoding:NSUTF8StringEncoding];
IDNum = [parser2 objectWithString:json_string2 error:&er];
}
}
As you can see if the connection failed it will show UIAlertView and two Buttons {ok , Refresh}.
I used this Method in case the refresh button been clicked to call viewDidLoad But not Working and giving me blank white view:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1){
[self viewDidLoad];
}
}
Any idea please ?
You should put your PHP Data Code in a method in it's own, so when you need to call that specifically you can, because you can't (or should I say shouldn't) call viewDidLoad manually. That should only be called automatically by UIViewController.
Example
- (void)viewDidLoad
{
[super viewDidLoad];
//iAds code
adview = [[ADBannerView alloc] initWithFrame:CGRectZero];
adview.frame = CGRectOffset(adview.frame, 0, 0);
adview.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifierPortrait];
adview.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
[self.view addSubview:adview];
adview.delegate = self;
self.adbanerinvesiable = NO;
}
-(void)viewWillAppear:(BOOL)animated /* or: -(void)viewDidAppear: */
{
[super viewWillAppear:animtaed];
[self refreshPHData];
}
-(void)refreshPHPData
{
//php data code
NSError *er;
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8888/newjson.php?number=1"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (response.length != 0){
NSString *json_string = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
listt = [parser objectWithString:json_string error:&er];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"No Internet conniction" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:#"Refresh", nil];
[alert show];
//for ID contet post
SBJsonParser *parser2 = [[SBJsonParser alloc] init];
NSURLRequest *request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8888/newjson.php?number=2"]];
NSData *response2 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:nil error:nil];
NSString *json_string2 = [[NSString alloc]initWithData:response2 encoding:NSUTF8StringEncoding];
IDNum = [parser2 objectWithString:json_string2 error:&er];
}
}
Also, when you call viewDidLoad from your UIAlertView, you are creating a second (and third and so forth) adview because you aren't removing the previous instance. Depending on how many times the alert is shown and viewDidLoad is called, you are going to see adview stacking on top of itself. So try instead:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1){
[self refreshPHPData];
}
}

Problem passing NSError back as a return parameter

I am having a problem passing an NSError object back. The first line of code to access the object (in this case, I inserted an NSLog) causes "EXC_BAD_ACCESS".
Is this because I am not explicitly creating an NSError object, but rather getting one from the NSURLRequest and passing it back? In this particular function (downloadFile:), some errors I want to retrieve from other functions, but I create an NSError on two other occasions in the function.
Any help is appreciated.
Here is the offending code:
-(void)someCode {
NSError *err = nil;
localPool = [[NSAutoreleasePool alloc] init];
if (!iap) {
iap = [[InAppPurchaseController alloc] init];
}
if (![self.iap downloadFile:#"XXXXX.plist" withRemoteDirectory:nil withLocalDelete:YES withContentType:#"text/xml" Error:&err] ) {
//"EXC_BAD_ACCESS" on calling NSLog on the next line?
NSLog(#"Error downloading Plist: %#", [err localizedDescription]);
[self performSelectorOnMainThread:#selector(fetchPlistFailed:) withObject:err waitUntilDone:NO];
[localPool drain], localPool = nil;
return NO;
}
//Removed the remainder of the code for clarity.
[localPool drain], localPool = nil;
return YES;
}
-(BOOL)downloadFile:(NSString *)fileName
withRemoteDirectory:(NSString *)remoteDirectory
withLocalDelete:(BOOL)withLocalDelete
withContentType:(NSString *)contentTypeCheckString
Error:(NSError **)error {
UIApplication *app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
NSError *localError = nil;
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
NSString *urlString = [NSString stringWithFormat:#"http://XXXXX/%#", fileName];
NSLog(#"Downloading file: %#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
NSHTTPURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&localError];
[req release];
if (response == nil || localError) {
NSLog(#"Error retrieving file:%#", [localError localizedDescription]);
if (error != NULL) {
*error = localError;
//THIS NSLog call works just fine.
NSLog(#"Error copied is:%#", [*error localizedDescription]);
}
[localPool drain], localPool = nil;
app.networkActivityIndicatorVisible = NO;
return NO;
}
//Rest of function omitted for simplicity.
}
I guess your NSError object is autoreleased and put on your localPool. You drained that localPool, thus destroying the NSError.
Do you really need localPool in every method? If not, just remove the localPools.
Also, it looks like you forgot to drain the localPool in someCode. Hopefully you just didn't copy it...
-(void)someCode {
NSError *err = nil;
localPool = [[NSAutoreleasePool alloc] init];
if (!iap) {
iap = [[InAppPurchaseController alloc] init];
}
if (![self.iap downloadFile:#"XXXXX.plist" withRemoteDirectory:nil withLocalDelete:YES withContentType:#"text/xml" Error:&err] ) {
....
[localPool drain], localPool = nil;
return NO;
}
[localPool drain], localPool = nil; // missing
}