Open App Store links without leaving the app, possible? - ios

In iOS app,
Anytime I call this function to open app store,
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"itms-apps://app-url"]];
The Original app will be deactivated.
The user will then have to restart the original app after they exit the App Store.
It’s very inconvenient way of installation.
Is there any way to open App Store links without leaving the app?
For example, opened as popup window,
after installation just close the popup window, and I can see the original app.
Updated :
I found a great example!
Like this game's popup.

Yes, we can open an App store link without leaving the existing app in IOS 6+.
you can use below for it.
#import <StoreKit/StoreKit.h>
SKStoreProductViewController *storeController = [[SKStoreProductViewController alloc] init];
storeController.delegate = delegate;
NSDictionary *productParameters = #{ SKStoreProductParameterITunesItemIdentifier : appStoreID };
[storeController loadProductWithParameters:productParameters completionBlock:^(BOOL result, NSError *error) {
//Handle response
}
Thanks

My version is here.
1) #import <StoreKit/StoreKit.h> and set SKStoreProductViewControllerDelegate
2) add delegate response method,
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController
{
// if user do cancel, close it
[viewController dismissViewControllerAnimated:YES completion:nil];
}
3) add store open code.
void SomeClassName::openAppStore(string appStoreId, string appUrl)
{
// below iOS 6.0
NSString *appUrlStatic = [NSString stringWithUTF8String:appUrl.c_str()];
// iOS 6.0 or above, appstore id is 9-digin number
NSString *appId = [NSString stringWithUTF8String:appStoreId.c_str()];;
// check SKStoreProductViewController API exist or not
if(NSClassFromString(#"SKStoreProductViewController")) {
SKStoreProductViewController *storeController = [[SKStoreProductViewController alloc] init];
storeController.delegate = self;
NSDictionary *productParameters = #{ SKStoreProductParameterITunesItemIdentifier : appId };
[storeController loadProductWithParameters:productParameters completionBlock:^(BOOL result, NSError *error) {
if (result) {
[self presentViewController:storeController animated:YES completion:nil];
} else {
[[[UIAlertView alloc] initWithTitle:#"Error Occur"
message:#"Error to open App Store."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] show];
}
}];
[storeController release];
} else {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrlStatic]];
}
}

Related

"sharerDidCancel:" is called after first successful share when Facebook app is not installed

I use a UIButton to share using Facebook's SDK 4.31.1. Once tapped, a share dialog is presented.
- (IBAction)btnSharePressed:(id)sender
{
[self displayShareDialog];
}
- (void)displayShareDialog {
FBSDKShareLinkContent *content = [self getShareContent];
if ([FacebookHandler isFacebookAppInstalled]) {
[FBSDKShareDialog showFromViewController:self
withContent:content
delegate:self];
} else {
FBSDKShareDialog * shareDialog = [[FBSDKShareDialog alloc] init];
[shareDialog setMode:FBSDKShareDialogModeBrowser];
[shareDialog setDelegate:self];
[shareDialog setFromViewController:self];
[shareDialog setShareContent:content];
[shareDialog show];
}
}
// Expects the URL of the scheme e.g. "fb://"
+ (BOOL)isFacebookAppInstalled {
NSArray* fbSchemes = #[#"fbapi://",
#"fb-messenger-api://",
#"fbauth2://",
#"fbshareextension://"];
BOOL isInstalled = false;
for (NSString* fbScheme in fbSchemes) {
isInstalled = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:fbScheme]];
if(isInstalled) {
break;
}
}
return isInstalled;
}
But when Facebook app is not installed, on every launch, on the first successful share the delegate method sharerDidCancel: is called and on any further successful share the correct delegate method sharer:didCompleteWithResults: is called.
I have correctly set the FacebookDisplayName and FacebookId in the plist file so it’s not about that.
I also tried switching FBSDKShareDialogModeBrowser with FBSDKShareDialogModeFeedBrowser with no luck.
Can someone shed some light on why the cancel method is called first, even though the share was completed successfully and why it is like that only after the first share?

Show App Store app page in app

There are some apps (like the free version of Cut the Rope) that present the App Store page of other apps directly in the app (probably using a modal view controller).
How do I implement this in my own app?
Example from Cut the Rope:
You can use SKStoreProductViewController for this, check out documentation for more detail
if ([SKStoreProductViewController class]) {
NSString *yourAppID = #"";//Give your app id here
NSDictionary *appParameters = #{SKStoreProductParameterITunesItemIdentifier :yourAppID};
SKStoreProductViewController *productViewController = [[SKStoreProductViewController alloc] init];
[productViewController setDelegate:self];
[productViewController loadProductWithParameters:appParameters completionBlock:nil];
[self presentViewController:productViewController animated:YES completion:nil];
}
One can implement a App Store page of any application within their own app by using the SKStoreProductViewController class.
NSString *strURL = #"" //Keep the App store URL here.
if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 6.0)
{
SKStoreProductViewController *storeProductViewController = [[SKStoreProductViewController alloc] init];
NSRange range = [strURL rangeOfString:#"/id"];
NSRange rangeID = {range.location + 3, 9};
NSString *strAppID = [strURL substringWithRange:rangeID];
NSLog(#"appid = %#", strAppID);
// Configure View Controller
[storeProductViewController setDelegate:self];
[storeProductViewController loadProductWithParameters:#{SKStoreProductParameterITunesItemIdentifier : strAppID}
completionBlock:^(BOOL result, NSError *error) {
if (error) {
NSLog(#"Error %# with User Info %#.", error, [error userInfo]);
} else {
}
}];
// Present Store Product View Controller
[self presentViewController:storeProductViewController animated:YES completion:nil];
}
The above code also extracts the app ID from the URL.
You can read about it in the class reference.

Multiple twitter login at same time IOS app

I have an application that i need to integrate with twitter login, for logging in via their twitter account. In the application we also have Twitter sharing option. Here i want to implement functionality to choose their account in which account they want to share the tweet. If user is logged in for only one account, then there should be provision to login to another account without logging out of existing logged-in account.
Well, this really compounds about 5 different topics in to one, and we can't write your entire app for you, but here are some helpful pointers.
When it comes to twitter, I use the STTwitter API (https://github.com/nst/STTwitter). What this does is takes all the twitter code, and dumbs it down for us less objective-c inclined programmers. The "README" file contains more information about what you'd be needing. You can find the developer tutorial at http://www.veasoftware.com/tutorials/2014/6/17/xcode-5-tutorial-ios-7-app-only-authentication-twitter-api-version-11. This also allows you to download the project to test, and copy and paste code from.
Youtube and Google are also great sources to find information. Right now your request is quite broad and encompases quite a few different aspects of twitter integration, work on them one at a time from the ground up.
====>Download Third Party Class FSHTwitterEngine.
{
[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:#"6XITOIDiXNajx7TQMKOh8qDxj" andSecret:#"w4F44ATueFsarNjGQ9WDdEudJCBJ8P0o5zeNON5bP9hIKhGls6"];
[[FHSTwitterEngine sharedEngine]setDelegate:self];
[[FHSTwitterEngine sharedEngine]loadAccessToken];
UIViewController *loginController = [[FHSTwitterEngine sharedEngine]loginControllerWithCompletionHandler:^(BOOL success) {
NSLog(success?#"L0L success":#"O noes!!! Loggen faylur!!!");
[self performSelector:#selector(TwitterPostMessage) withObject:nil afterDelay:1.0];
}];
[self presentViewController:loginController animated:YES completion:nil];
}
-(void)TwitterPostMessage
{
UIImage *aimg = [UIImage imageNamed:#"mark"];
// [[FHSTwitterEngine sharedEngine]postTweet:#"Hepp adsfihdf sdfhihdsfh" withImageData:UIImagePNGRepresentation(aimg)];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
#autoreleasepool {
//NSString *tweet = [alertView textFieldAtIndex:0].text;
// id returned = [[FHSTwitterEngine sharedEngine]postTweet:#"Post of image"];
id returned = [[FHSTwitterEngine sharedEngine]postTweet:#"Hi Successfully Post Twitter..." withImageData:UIImagePNGRepresentation(aimg)];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *title = nil;
NSString *message = nil;
if ([returned isKindOfClass:[NSError class]])
{
NSError *error = (NSError *)returned;
title = [NSString stringWithFormat:#"Error %d",error.code];
message = error.localizedDescription;
} else {
NSLog(#"%#",returned);
title = #"Tweet Posted";
message = #"Post of image";
}
dispatch_sync(dispatch_get_main_queue(), ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}
});
}
});
}

Using the Google APIs with OAuth 2.0 for gmail login in iPhone

I have found a services from Google which provides to access to Google APIs for various Google Services. I could set up a project in iPhone and create API access for iOS applications (via OAuth2.0) and native applications. I wanted to use the native API for my iPhone app. It API gives me email,fullname,firstname,lastname,google_id,gender,dob,profile_image. How do I use these in my iPhone Application, Any sample apps, snippets available?
Please help me.
Here is my code :
-(void) loadGmail_Login
{
NSString *keychainItemName = nil;
if ([self shouldSaveInKeychain]) {
keychainItemName = kKeychainItemName;
}
// For GTM applications, the scope is available as
NSString *scope = #"http://www.google.com/m8/feeds/";
// ### Important ###
// GTMOAuthViewControllerTouch is not designed to be reused. Make a new
// one each time you are going to show it.
// Display the autentication view.
GTMOAuthAuthentication *auth;
auth = [GTMOAuthViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName];
GTMOAuthViewControllerTouch *viewController = [[[GTMOAuthViewControllerTouch alloc]
initWithScope:scope
language:nil
appServiceName:keychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)] autorelease];
// You can set the title of the navigationItem of the controller here, if you want.
// Optional: display some html briefly before the sign-in page loads
NSString *html = #"<html><body bgcolor=silver><div align=center>Loading sign-in page...</div></body></html>";
[viewController setInitialHTMLString:html];
[[self navigationController] pushViewController:viewController animated:YES];
}
- (void)viewController:(GTMOAuthViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuthAuthentication *)auth
error:(NSError *)error
{
if (error != nil)
{
// Authentication failed (perhaps the user denied access, or closed the
// window before granting access)
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; // kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
NSString *str = [[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"%#", str);
}
[self setAuthentication:nil];
}
else
{
// save the authentication object
[self setAuthentication:auth];
// Just to prove we're signed in, we'll attempt an authenticated fetch for the
// signed-in user
[self doAnAuthenticatedAPIFetch];
}
}
- (void)doAnAuthenticatedAPIFetch
{
NSString *urlStr;
// Google Contacts feed
//
// https://www.googleapis.com/oauth2/v2/userinfo
urlStr = #"http://www.google.com/m8/feeds/contacts/default/thin";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[mAuth authorizeRequest:request];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded
NSString *str = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"API response: %#", str);
GGCXml_Adaptor *localAlphabetXMLParser = [[GGCXml_Adaptor alloc] init];
[localAlphabetXMLParser processBooksXML:data];
[localAlphabetXMLParser release];
// [self updateUI];
} else {
// fetch failed
NSLog(#"API fetch error: %#", error);
}
}
- (void)setAuthentication:(GTMOAuthAuthentication *)auth {
[mAuth autorelease];
mAuth = [auth retain];
}
First you will need to get token from Google API, For this 1st step you will have to follow this tutorial and in the end of this link there is whole source code for iOS for getting token from google API
http://technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/
Then in the next step you have to send that token to Google API to request user Data, I just needed the first step So I am sharing my searchings
Try this Tutorial and Source code Link.. It's works fine for me.
1. Tutorial Reference: http://technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/
2. Api Reference : https://code.google.com/apis/console/
3. Source code: https://github.com/emysa341/Login-with-gmail-google-g--using-oath-2.0-protocol/archive/master.zip
i think this will help anybody else
Follow the below steps to integrate gmail with your application .
1.Add following classes to you project .
GTMHTTPFetcher.h , GTMHTTPFetcher.m ,GTMOAuth2Authentication.h, GTMOAuth2Authentication.m,GTMOAuth2SignIn.h,GTMOAuth2SignIn.m,GTMOAuth2ViewControllerTouch.h,GTMOAuth2ViewControllerTouch.m,GTMOAuth2ViewTouch.xib,SBJSON.h , SBJSON.m
you will get these classes here : https://github.com/jonmountjoy/Force.com-iOS-oAuth-2.0-Example
Note : if you are working under ARC Environment then you have to disable the ARC for following files :
GTMHTTPFetcher.m , GTMOAuth2Authentication.m , GTMOAuth2SignIn.m, GTMOAuth2ViewControllerTouch.m
To disable ARC for source files in Xcode 4, select the project and the target in Xcode. Under the target "Build Phases" tab, expand the Compile Sources build phase, select the library source files, then press Enter to open an edit field, and type -fno-objc-arc as the compiler flag for those files.
2. add the following frameworks
security.framework , systemConfiguration.framework
3. Register your app to google api console …. here : https://code.google.com/apis/console
Then go to ApiAccess section , create client id for iOS app .
then you will get clientID, ClientSecret and RedirectUrl
**4. Now it's time for coding . . . .**
create a signIn button in your controller and set the action for that . Here when the user click the button SignInGoogleButtonClicked method gets called .
//import GTMOAuth2Authentication , GTMOAuth2ViewControllerTouch
#define GoogleClientID #"paster your client id"
#define GoogleClientSecret #"paste your client secret"
#define GoogleAuthURL #"https://accounts.google.com/o/oauth2/auth"
#define GoogleTokenURL #"https://accounts.google.com/o/oauth2/token"
-(void) SignInGoogleButtonClicked
{
NSURL * tokenURL = [NSURL URLWithString:GoogleTokenURL];
NSString * redirectURI = #"urn:ietf:wg:oauth:2.0:oob";
GTMOAuth2Authentication * auth;
auth = [GTMOAuth2Authentication authenticationWithServiceProvider:#"google"
tokenURL:tokenURL
redirectURI:redirectURI
clientID:GoogleClientID
clientSecret:GoogleClientSecret];
auth.scope = #"https://www.googleapis.com/auth/plus.me";
GTMOAuth2ViewControllerTouch * viewcontroller = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth
authorizationURL:[NSURL URLWithString:GoogleAuthURL]
keychainItemName:#"GoogleKeychainName" delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[self.navigationController pushViewController:viewcontroller animated:YES];
}
//this method is called when authentication finished
- (void)viewController:(GTMOAuth2ViewControllerTouch * )viewController finishedWithAuth:(GTMOAuth2Authentication * )auth error:(NSError * )error
{
if (error != nil) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error Authorizing with Google"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Alert !"
message:#"success"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}

Liking a Facebook page from native iOS application

I am attempting to LIKE a business Facebook Like page (facebook.com/[LikePage]) from my native iOS application. I have used FB iOS SDK for login/logout purpose.
I have implemented the LIKE button similar to http://angelolloqui.com/blog/10-Facebook-Like-Button-on-iOS, which is an implementation of the social plugin on a webview. I did so, because of my understanding that to implement a custom LIKE button, I need to use the Built-in Like provided by FB which in turn would require that my actions be approved by FB.
However, it was brought to my notice that the social plugin implementation cannot be used in an iOS native application and can be used only in a mobile web app.
So, here are my questions :-
Is it true that native iOS applications cannot use the social plugin provided by facebook to like a Facebook Page ?
Is it true that in order to build a custom Like button and not the plugin, I need to use the Built-in Likes provided by Facebook, which in turn would require approval of my action types ? (In my case, LIKE a Page)
All I need is some concrete documentation which clearly lets me know which is the best way forward.
FYI, the business page URL's that need to be LIKEd, come dynamically from server.
Thanks in Advance.
There's no API or automatic method to like facebook pages. The built-in open graph action, once approved, allows you to like other URLs which have Open Graph meta tags on them but not Facebook Pages.
The Like button plugin should work in a webview as far as I know.
You can just use a regular NSURLRequest to like the page, or use another library to make a post call to: https://graph.facebook.com/{PAGE_OR_OBJECT_ID}/likes. Make sure you add the acces_token as a parameter.
I use AFNetworking to post requests:
NSURL *baseURL = [NSURL URLWithString:#"https://graph.facebook.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
NSString *link = [NSString stringWithFormat:#"/%#/likes", myObjectID];
NSDictionary *params = #{#"access_token" : FBSession.activeSession.accessToken};
[httpClient postPath:link parameters:params success:^(AFHTTPRequestOperation *op, id result) {
NSLog(#"result %#", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error %#", error);
}];
An update to this post:-
"With the release of the Facebook SDK version 4.28.0, the Like Button for iOS is deprecated. It will be supported until February 5, 2018."
https://developers.facebook.com/docs/sharing/ios/like-button
try this Code:
I think this will surely help you:
Fb like Widget can be embedded in our application. You just have to add a webView and get the Fb Like Widget html code/URL here.
in ViewController.h where you want to add fb like button:
#import <UIKit/UIKit.h>
#interface TestViewController : UIViewController <UIWebViewDelegate>
#property (strong, nonatomic) UIWebView * fbLikeWebView;
-(void)embedFBLikeButton;
#end
in TestViewController.m
#import "AboutUsViewController.h"
#implementation AboutUsViewController
#synthesize fbLikeWebView = _fbLikeWebView;
- (void)viewDidLoad
{
[super viewDidLoad];
//Add this code for FbLike Webview
self.fbLikeWebView = [[UIWebView alloc] initWithFrame: CGRectMake(100.0, 50.0, 55.0, 70.0)];
_fbLikeWebView.opaque = NO;
_fbLikeWebView.backgroundColor = [UIColor clearColor];
_fbLikeWebView.delegate = self;
[self.view addSubview:_fbLikeWebView];
for (UIScrollView *subview in _fbLikeWebView.subviews)
{
if ([subview isKindOfClass:[UIScrollView class]]) {
subview.scrollEnabled = NO;
subview.bounces = NO;
}
}
}
then in ViewWillAppear method call the enbeddFBLikeButton Method to add the fbLike button wigdet on web view:
-(void)viewWillAppear:(BOOL)animated
{
[self embedFBLikeButton];
[_fbLikeWebView reload];
}
-(void)embedFBLikeButton
{
NSString *facebookUrl = //here paste the url you get from fb developer link above;
[self.fbLikeWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:facebookUrl]]];
}
You conform to UIWebViewDelegate now its turn to defining th edelegate method here:
#pragma mark - WebView Delgate Methods
- (BOOL)webView:(UIWebView *)webview shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if ([request.URL.lastPathComponent isEqualToString:#"login.php"])
{
[self login];
return NO;
}
return YES;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[_fbLikeWebView stopLoading];
}
This method for login the user to facebook Account:
- (void)login
{
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:#[#"publish_actions", #"publish_stream", #"user_photos"]]];
[[FBSession activeSession] openWithBehavior: FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
// call the legacy session delegate
//Now the session is open do corresponding UI changes
if (session.isOpen) {
FBRequest *me = [FBRequest requestForMe];
[me startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *my,
NSError *error) {
if (!my) {
NSLog(#"Facebook error:\n%#", error.description);
[[[UIAlertView alloc] initWithTitle: #"Error"
message: #"Facebook Login error."
delegate: self
cancelButtonTitle: #"Ok"
otherButtonTitles: nil, nil] show];
return;
}
}];
[_fbLikeWebView reload];
[[[UIAlertView alloc] initWithTitle: #""
message: #"Successfully Login. Please click on like button"
delegate: self
cancelButtonTitle: #"Ok"
otherButtonTitles: nil, nil] show];
}
break;
case FBSessionStateClosedLoginFailed:
{
[_fbLikeWebView reload];
}
break;
default:
break; // so we do nothing in response to those state transitions
}
}];
}
Enjoy Coding!!!

Resources