I'm showing back button in webview if canGoBack is true.
It works fine but for one particular webpage even though there's no back page to go back, the webview says cangoback as true while cangoback should have been false.
Update
Here is the code snippet to init my webview
-(void)initWebView{
WKUserContentController* userContentController = WKUserContentController.new;
NSString* documentCookie = [self documentCookie];
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: documentCookie
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
// again, use stringWithFormat: in the above line to inject your values programmatically
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
webViewConfig.userContentController = userContentController;
self.webviewObj = [[WKWebView alloc] initWithFrame:CGRectMake(self.vuParent.frame.origin.x, self.vuParent.frame.origin.y, self.vuParent.frame.size.width, self.vuParent.frame.size.height) configuration:webViewConfig];
self.webviewObj.UIDelegate = self;
[self.webviewObj setBackgroundColor:[UIColor whiteColor]];
self.webviewObj.translatesAutoresizingMaskIntoConstraints=false;
[self.vuParent addSubview:self.webviewObj];
}
Here is how I load a request in my webview
-(void)completeWebRequest
{
NSString* urlToRequestStr = #"";
if ([[self targetUrl] length]) {
urlToRequestStr = [self targetUrl];
}
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlToRequestStr]];
if (self.isPOST) {
NSMutableData *body = [[NSMutableData alloc] initWithData:[self.postParams dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[body length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
}
[self initWebView];
self.webviewObj.scrollView.scrollEnabled=false;
[self.view setBackgroundColor:[UIColor whiteColor]];
[self.webviewObj setOpaque:false];
self.webviewObj.navigationDelegate = self;
[self setOriginalUrlToRequest:tempRequest];
[[self webviewObj] loadRequest:tempRequest];
}
Here is how I check if back button needs to be shown or not.
[self setBackButtonCheckTimer:[NSTimer timerWithTimeInterval:0.1 target:self selector:#selector(chkBackBtn) userInfo:nil repeats:true]];
- (void) chkBackBtn {
if ([[self webviewObj] canGoBack]) {
[[self navigationItem] setLeftBarButtonItem:[self bkButton]];
}
else{
[[self navigationItem] setLeftBarButtonItem:nil];
}
}
There is a way that you can use it in order to debug such a problem.
The canGoBack method works based on backForwardList.
You can validate what you have in the list and change it.
Related
i am trying to load a url in uiwebview in xcode and it is loading just fine but problem is that there is ZERO user interaction with it. i can not touch any button on it or can not even scroll it. i have already tried Allow Arbitrary Loads = YES in info.plist but nothing happened here is my code.
[webPage setDelegate:self];
[webPage loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://url.com"]]];
[webPage addSubview:activityIndicatorView];
here is more code from .h:
#interface ViewController : UIViewController<UIWebViewDelegate>{
IBOutlet UIWebView *webPage;
}
#property (retain, nonatomic) IBOutlet UIWebView *webPage;
its s simple uiwbview from interface builder in a simple uiviewcontroller.
and here is my info.plist
I figure out that problem might be here in this part of the code. there is a menu in my uinavigationbar as well which is loading xml menu. wait i will post my code.
- (void) makeMenu{
#try {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^{
NSURL *url=[NSURL URLWithString:#"http://url/xml-menu.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
rssOutputData = [[NSMutableArray alloc]init];
xmlParserObject =[[NSXMLParser alloc]initWithData:urlData];
[xmlParserObject setDelegate:self];
[xmlParserObject parse];
}
dispatch_async(dispatch_get_main_queue(), ^{
sideMenu.delegate = self;
NSInteger count;
NSMutableArray *itemsArry = [[NSMutableArray alloc] init];
count = [rssOutputData count];
for (int i = 0; i < count; i++){
BTSimpleMenuItem *item = [[BTSimpleMenuItem alloc]initWithTitle:[[rssOutputData objectAtIndex:i]xmltitle] image:[UIImage imageNamed:#"arrow.png"]
onCompletion:^(BOOL success, BTSimpleMenuItem *item) {
[webPage loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[[rssOutputData objectAtIndex:i]xmllink]]]];
}];
[itemsArry addObject:item];
}
NSArray *itemSarry=[[NSArray alloc] initWithArray:itemsArry];
sideMenu = [[BTSimpleSideMenu alloc]initWithItem:itemSarry addToViewController:self];
});
});
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
}
when i call this method in viewdidload uiwebview stop responding. And if i do not call this part uiwebview works just fine. please help me i need this menu as well.
Try this:
webPage.userInteractionEnabled = YES;
i am creating 2 buttons one for like and one for dislike when i click like button its disable and also disable dislike button same time.and so on. and its not change when i am run the application second time. i am implemented for that its work but problem is that when i run my application second time once again that button enable. problem is that i don't want that button same button enable.please help me what is the problem in my code
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:102/255.0
green:102/255.0 blue:204/255.0 alpha:1.0];
self.navigationController.navigationBar.titleTextAttributes =
#{NSForegroundColorAttributeName : [UIColor whiteColor]};
smsdisplaytext.editable=NO;
smsdisplaytext.backgroundColor= [UIColor colorWithRed:102/255.0 green:102/255.0
blue:204/255.0 alpha:1.0];
self.navigationItem.title=#"Insta SMS";
[ self getSmsData];
[self smsdisplay];
[self getLike];
}
-(void)sendlike
{
NSURL *url = [NSURL URLWithString:
#"http://sms.instatalkcommunications.com/apireq/AddRatingForSMS"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:#"t"];
[request setPostValue:#"admin" forKey:#"h"];
[request setPostValue:[NSString stringWithFormat:#"%#",self.Id] forKey:#"cid"];
[request setPostValue:[NSString stringWithFormat:#"%d",1234567890] forKey:#"token"];
[request setPostValue:#"test#test.com" forKey:#"email"];
[request setTag:2];
[request setPostValue:#"true" forKey:#"like"];
[request setDelegate:self];
[request startAsynchronous];
}
-(void)senddislike
{
NSURL *url = [NSURL URLWithString:
#"http://sms.instatalkcommunications.com/apireq/AddRatingForSMS"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:#"t"];
[request s etPostValue:#"admin" forKey:#"h"];
[request setPostValue:[NSString stringWithFormat:#"%#",self.Id] forKey:#"cid"];
[request setPostValue:[NSString stringWithFormat:#"%d",1234567890] forKey:#"token"];
[request setPostValue:#"test#test.com" forKey:#"email"];
[request setPostValue:#"false" forKey:#"Like"];
[request setTag:3];
[request setDelegate:self];
[request startAsynchronous];
}
- (void) requestFinished:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
responseString = [request responseString];
NSLog(#"%#",responseString);
if(request.tag==1)
{
SBJsonParser *parser = [[SBJsonParser alloc] init] ;
NSArray *jsondata = [parser objectWithString:responseString];
NSLog(#"%#",jsondata);
for (NSObject* item in jsondata)
{
likelabel.text = [[item valueForKey:#"Liked"] stringValue];
dislikelabel.text = [[item valueForKey:#"Disliked"] stringValue];
}
}
else if(request.tag==2)
{
[self getLike];
}
/////// getting comment
else if(request.tag==4)
{
// get comments
SBJsonParser *parser = [[SBJsonParser alloc] init] ;
NSMutableArray *jsondata = [parser objectWithString:responseString];
for(int i=0;i<jsondata.count;i++)
{
NSObject *temp = [jsondata objectAtIndex:i];
NSMutableDictionary *message = [[NSMutableDictionary alloc] init];
message[kMessageContent]=[temp valueForKey:#"Comment"];
message[#"Timestamp"]=[self dateWithJSONString:[temp valueForKey:#"CreatedDate"]];
last=[[temp valueForKey:#"Id"] integerValue];
[_chatController addNewMessage:message];
}
}
else
{
////post comment
[self getComment];
}
}
//this method for getting like and dislike
-(void)getLike
{
NSString *url = [NSString
stringWithFormat:#"http://sms.instatalkcommunications.com/apireq/GetRatingsForSMS?
t=1&h=admin&cid=%#&token=1234567890&email=test#test.com",self.Id];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setRequestMethod:#"GET"];
[request setTag:1];
[request setDelegate:self];
[request startAsynchronous];
}
// here for like button
- (IBAction)btnlike:(id)sender
{
NSLog(#"keypress");
[self sendlike];
[self getLike];
UIButton *btnlike = (UIButton *) sender;
btnlike.enabled = NO;
UIButton *btndislike = (UIButton *) sender;
btndislike.enabled = NO;
}
//here i am action for dislike button
- (IBAction)btndislike:(id)sender
{
NSLog(#"keypress");
[self senddislike];
[self getLike];
UIButton *btndislike = (UIButton *) sender;
btndislike.enabled = NO;
_btnlike.enabled = NO;
}
#end
As I'm not an native english speaker, I hope I've understood correctly what you are trying to achieve.
If I understand correctly, You have a 'Like' and 'Dislike' buttons, and when the user presses on one of them, you want both to be disabled,
Which is working correctly for the current run.
But, if I understand correctly, the next time the app runs, the buttons are 'reset' to be enabled, and you don't want that,
You want the button be disabled every time the app runs.
If I did understood you correctly, the way to 'save' state of objects is using the NSUserDefaults.
You might have a better way to implement it than my example below, but it should do the trick, and also give you a better understanding on how to implement it, incase you need to modify my code.
Add the following method:
-(void)disableButtons {
[[NSUserDefaults standardUserDefaults] setBool: YES forKey: #"buttonsDisabled"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
now, at the end of the 'Like' and 'Dislike' buttons, just call the following methods by adding to your code:
[self disableButtons]
Now, add the following to viewDidLoad:
// someplace in viewDidLoad
BOOL bottunsDisabled = [[NSUserDefaults standardUserDefaults] boolForKey: #"buttonsDisabled"];
if(buttonsDisabled) {
self.btndislike.enabled = NO;
self.btnlike.enabled = NO;
}
The buttons defaults state are enabled, so the above code will change them, incase they have been disabled in previous runs.
Note that I also assumed you have a reference to the buttons (I assume you've created them in interface builder), if not, just create a property/ivar that will hold a reference to them.
And as Ian MacDonald mentioned above, in the 'Like' button method, you are disabling only the 'Like' button twice, and not disabling the 'Dislike' button.
In order to fix it, change the code to the following (again, I assume you have some sort of reference to both of them):
- (IBAction)btnlike:(id)sender
{
NSLog(#"keypress");
[self sendlike];
[self getLike];
self.btnlike.enabled = NO;
self.btndislike.enabled = NO;
[self disableButtons];
}
As I've said above, I'm not an native english speaker,
So I hope my answer was clear enough.
If something isn't clear, just tell me and I'll try to rephrase it.
Good luck mate!
I am new to iPhone programming using below code i am login in Facebook and fetching data from Facebook like email id,username after that emailid i am sending to server.But my problem is if already login in Facebook means automatically its calling
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id)user in this method email id sending to server.I don't want like this if i click on button then only i want to fetch Facebook email id and send to server.Please can any one give some idea how to solve it.
-(void)viewdidload
{
FBLoginView *fbLoginview =
[[FBLoginView alloc] initWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions",#"email",nil] defaultAudience:FBSessionDefaultAudienceFriends];
fbLoginview.frame = CGRectMake(30, 10, 200, 30);
for (id obj in fbLoginview.subviews)
{
if ([obj isKindOfClass:[UIButton class]])
{
loginWithFbButton = obj;
loginWithFbButton.frame = CGRectMake(0, 0, 200, 30);
[loginWithFbButton setBackgroundColor:[UIColor colorWithRed:69.0/255.0 green:115.0/255.0 blue:185.0/255.0 alpha:1]];
[loginWithFbButton setBackgroundImage:nil forState:UIControlStateNormal];
[loginWithFbButton setBackgroundImage:nil forState:UIControlStateSelected];
[loginWithFbButton setBackgroundImage:nil forState:UIControlStateHighlighted];
[loginWithFbButton.layer setBorderWidth:1.0f];
[loginWithFbButton.layer setBorderColor:[UIColor colorWithRed:225.0/255.0 green:227.0/255.0 blue:231.0/255.0 alpha:0.6].CGColor];
loginWithFbButton.layer.masksToBounds = YES;
loginWithFbButton.layer.cornerRadius = 5;
[loginWithFbButton setTitle:#" Get info from Facebook" forState:UIControlStateNormal];
[loginWithFbButton.titleLabel setFont:[UIFont fontWithName:#"HelveticaNeue" size:13]];
loginWithFbButton.titleLabel.textAlignment = NSTextAlignmentCenter;
loginWithFbButton.titleLabel.backgroundColor = [UIColor clearColor];
loginWithFbButton.titleLabel.textColor = [UIColor whiteColor];
CAGradientLayer *gradient1 = [CAGradientLayer layer];
gradient1.frame = loginWithFbButton.bounds;
UIColor *startColour1 = [UIColor colorWithRed:46.0/255.0 green:174.0/255.0 blue:225.0/255.0 alpha:1.0f];
UIColor *endColour1 = [UIColor colorWithRed:46.0/255.0 green:119.0/255.0 blue:225.0/255.0 alpha:1.0f];
gradient1.colors = [NSArray arrayWithObjects:(id)[startColour1 CGColor], (id)[endColour1 CGColor], nil];
[loginWithFbButton.layer insertSublayer:gradient1 atIndex:0];
[fbLoginview addSubview:loginWithFbButton];
}
if ([obj isKindOfClass:[UILabel class]])
{
UILabel * loginLabel = obj;
loginLabel.text = nil;
loginLabel.textAlignment = NSTextAlignmentCenter;
loginLabel.frame = CGRectMake(0, 0, 271, 26);
}
}
fbLoginview.delegate = self;
[loginTempview3 addSubview:fbLoginview];
}
fetching
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
NSLog(#"Loginvieewww");
// self.profilePic.profileID = user.id;
//self.profilePic.profileID = #"1772134559592493";
// NSLog(#"usr_id::%#",user.id); NSLog(#"%#",user);
NSLog(#"usr_first_name::%#",user.first_name);
NSString *emailiddd=[NSString stringWithFormat:#"%#",[user objectForKey:#"email"]];
NSLog(#"%#",emailiddd);
NSLog(#"usr_last_nmae::%#",user.last_name);
NSLog(#"usr_Username::%#",user.username);
NSLog(#"usr_b_day::%#",user.birthday);
NSString *post = [NSString stringWithFormat:#"email=%#",emailiddd];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://54.221.218.162/index.php/api/userClass/registerFBUser/format/xml"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"Aslam here");
NSLog(#"%#",request);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [NSMutableData data];
NSLog(#"%#",webData);
}
else
{
}
}
Thanks
Aslam
I have a login screen and when a button is pressed this code executes:
- (IBAction)btnLogin:(id)sender {
[username resignFirstResponder];
[password resignFirstResponder];
Auth *authRequest = [[Auth alloc] init];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:APIHOST path:#"/authenticate"];
[authRequest setUrl:url];
[authRequest setUsername:[username text]];
[authRequest setPassword:[password text]];
[authRequest authenticate];
[self performSegueWithIdentifier:#"Login2Tab" sender:self];
}
This works well and the segue executes as expected (So I know the segue exists and its identified correctly in the storyboard). I however don't want to perform the segue until the connection has finished loading so this implementation file is my delegate for NSURLConnection and at the bottom I have (and the if/else on responseCode does work)..:
// Close the connection
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
if(responseCode == 200) {
[self performSegueWithIdentifier:#"Login2Tab" sender:self];
} else {
NSLog(#"Bad.. bad.. bad...");
}
NSLog(#"Connection Closed.");
}
(When I put the performSegueWithIdentifer in the connectionDidFinishLoading I comment out the performSegueWithIdentier from above...).
But now the app always crashes stating:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver (LoginViewController: 0x7163640) has no segue with identifier 'Login2Tab''
Which is where I am stuck because it works when its not called from within the connectionDidFinishLoading...
Just wanted to say I have this resolved altho I am not entirely sure how.
Basically this line in my ViewController
[authRequest authenticate];
Was loading a method in an external class file:
- (void)authenticate {
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:APIHOST path:#"/authenticate"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:3];
NSString *postString = [[NSString alloc] initWithFormat:#"email=%#&password=%#", [username text], [password text]];
[request setValue:APIKEY forHTTPHeaderField:#"apikey"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setURL:url];
if ([NSURLConnection canHandleRequest:request]) {
NSLog(#"Starting network connection");
NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[myConnection start];
} else {
//Error cannot activate network request from device
}
}
The delegates for the NSURLConnection were in the viewcontroller... and I could see them being accessed when the method was complete however I couldn't perform the segue from them. By moving this function from the class file to my viewcontroller I was able to call my segue's from the delegate method of connectionDidFinishLoading....
Strange but worked.
I am beginner iOS apps developer .I have tried following link codes.It's playing good but I need selected audio file path and how to upload to server in selected audio,kindly help out.Audio code Reference url
-(IBAction)clickFileuploadbtn:(id)sender;
{
NSLog(#"2");
picker1 =
[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker1.delegate = self;
picker1.allowsPickingMultipleItems = YES;
picker1.prompt = NSLocalizedString (#"Add songs to play", "Prompt in media item picker");
// The media item picker uses the default UI style, so it needs a default-style
// status bar to match it visually
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault animated: YES];
[self presentModalViewController: picker1 animated: YES];
[picker1 release];
// [Uploads FileUpload];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"%# %d",mediaItemCollection,mediaItemCollection.count);
NSArray *newMediaItem= [mediaItemCollection items];
MPMediaItem *item=[[newMediaItem objectAtIndex:0] retain];
[self uploadMusicFile:item];
}
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"cancel");
}
- (void) uploadMusicFile:(MPMediaItem *)song
{
NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [NSString stringWithFormat:#"%#",url];
NSLog(#"path %#",path);
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
NSLog(#"data %#" ,data);
NSString *audioName = #"myAudio.caf";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.176:1001/api?type=iphoneupload"]];
[request addData:data withFileName:audioName andContentType:#"audio/caf" forKey:#"audioFile"];
[request setDelegate:self];
[request setTimeOutSeconds:500];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
NSData *webData = [[NSData alloc] initWithData:[request responseData]];
NSString *strEr = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"strEr %#",strEr);
}
- (void) uploadRequestFailed:(ASIHTTPRequest *)request
{
NSLog(#"responseStatusCode %i",[request responseStatusCode]);
NSLog(#"responseString %#",[request responseString]);
NSError *error = [request error];
NSLog(#"error %#",error);
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
}