Facebook connect - facebook

Is there anyway of using facebook connect within an iPad or iPhone application.
The idea would be to sign into this App and then be able to see which of my facebook user's also use the app and its features.

Yep.
The new version:
Docs: http://developers.facebook.com/docs/guides/mobile/
Code: none, you write it yourself using the Graph API
The old version:
Docs: http://wiki.developers.facebook.com/index.php/Facebook_iPhone_SDK
Code: http://github.com/facebook/facebook-iphone-sdk/

Please follow the tutorial for Facebook SDK integration for you app from below link:
http://www.raywenderlich.com/77/how-to-post-on-facebook-with-your-iphone-app
Then test the app. If you need to run the same code for iPad also, and if you want to resize Facebook controls for iPad, just follow instructions from:
http://forum.developers.facebook.net/viewtopic.php?id=54307
But take care of few things:
In FBDialog.m
1) for 'postDismissCleanup' function don't comment the line,
[self removeObservers];
Otherwise your application will start crashing.
2) Replace both of these functions
- (void)keyboardWillHide:(NSNotification*)notification {
//UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
/*if (UIInterfaceOrientationIsLandscape(orientation)) {
_webView.frame = CGRectInset(_webView.frame,
kPadding + kBorderWidth,
kPadding + kBorderWidth + _titleLabel.frame.size.height);
}*/
_showingKeyboard = NO;
}
- (void)keyboardWillShow:(NSNotification*)notification {
//UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
/*if (UIInterfaceOrientationIsLandscape(orientation)) {
_webView.frame = CGRectInset(_webView.frame,
-(kPadding + kBorderWidth),
-(kPadding + kBorderWidth) - _titleLabel.frame.size.height);
}*/
_showingKeyboard = YES;
}

Related

ITunes review URL and iOS 7 (ask user to rate our app) AppStore show a blank page

Does anybody knows if the technique used to ask the user to rate our app and open for him the App Store directly on the rating page is still working on iOS 7 ?
I used to open this url from my app :
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=353372460&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software
But it looks like it's not working anymore (AppStore show a blank page). I have also tried this url wihout luck:
http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8&id=353372460
Starting with iOS7 the URL has changed and cannot direct for the review page but only to the app
itms-apps://itunes.apple.com/app/idAPP_ID
Where APP_ID need to be replaced with your Application ID. Based on the App ID from the question it would be the following
itms-apps://itunes.apple.com/app/id353372460
Notice the id in front of the number ... that string is is id353372460, not just 353372460
For anything pre iOS7 the 'old' URL needs to be used, only those could get you straight to the review page. You should also take note that these calls will only work on devices. Running them in the simulator will do nothing since the simulator does not have the App Store app installed.
Have a look at for instance Appirater for an implementation. https://github.com/arashpayan/appirater
Can't help you with phonegap specifics (never used it). But it basically comes down to checking the iOS version your user is running and then either use the old URL or then new iOS7 URL.
The following URL works perfectly on iOS 7.1:
http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=xxxxxxxx&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8
where the xxxxxxxx is your app ID.
UPDATE. Works on iOS 9.3.4 and iOS 10 GM (by Jeet)
This works on my end (Xcode 5 - iOS 7 - Device!):
itms-apps://itunes.apple.com/app/idYOUR_APP_ID
For versions lower than iOS 7 use the old one:
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=YOUR_APP_ID
One-Line-of-Code Simple Alternative: ** Also See Simulator Comments Below **
http://itunes.apple.com/app/idAPP_ID
EDIT: Now that iOS 7.1 allows direct-link to the Reviews tab in the App Store, it's worth investing the extra lines of code to get there directly: see other answers for the rest.
here we are using http: instead of itms-apps:, let iOS do the rest of the work
I get the same results testing on iOS 6.1 & 7 devices (iPad/iPhone/iPod touch 4)
Specifically, this shortcut, for iOS 6 takes the user to the Details tab and not the Reviews tab.
The Purple+Software link gets the user all the way to the Reviews tab in iOS 6, which is obviously preferred if you know how to check the OS.
Important note: This will cause error in the simulator for iOS 5.1, 6.1 and 7.Cannot Open Page Safari can not open the page because the address is invalid (we know it is a valid URL outside the simulator, on any browser)
Just to be clear: On iOS 7: http:// provides the same experience as itms-apps: with no noticeable delay. * keep in mind that the simulator behavior noted above. This is not entire dissimilar from trying to access the camera via a simulator: the simulator is not the place to test it. *
It's not clear which versions of iOS this is supported by, but as part of iOS 10.3 there's a new query parameter that can be added to the URL: action=write-review. I have tested this on iOS 10.2 and 9.3.5 and it works. However, it does not work on iOS 7.1.2, so support was added between iOS 8.0 and 9.3.5. Further investigation is required!
Example: https://itunes.apple.com/app/id929726748?action=write-review&mt=8
This will open the "Write a Review" dialogue, rather than just showing the review tab.
Opening review page directly from app is possible in iOS7.
Please use the following url...
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=YOUR_APP_ID
This will definitely works.. :)
+ (NSString *)getReviewUrlByAppId:(int)appId
{
NSString *templateReviewURL = #"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APP_ID";
NSString *templateReviewURLiOS7 = #"itms-apps://itunes.apple.com/app/idAPP_ID";
NSString *templateReviewURLiOS8 = #"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=APP_ID&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software";
//ios7 before
NSString *reviewURL = [templateReviewURL stringByReplacingOccurrencesOfString:#"APP_ID" withString:[NSString stringWithFormat:#"%d", appId]];
// iOS 7 needs a different templateReviewURL #see https://github.com/arashpayan/appirater/issues/131
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 7.1)
{
reviewURL = [templateReviewURLiOS7 stringByReplacingOccurrencesOfString:#"APP_ID" withString:[NSString stringWithFormat:#"%d", appId]];
}
// iOS 8 needs a different templateReviewURL also #see https://github.com/arashpayan/appirater/issues/182
else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
reviewURL = [templateReviewURLiOS8 stringByReplacingOccurrencesOfString:#"APP_ID" withString:[NSString stringWithFormat:#"%d", appId]];
}
return reviewURL;
}
The review link has once again broken in iOS9. In doing some experimenting, I figured out that Apple reverted it back to how it was before iOS7. So you have to do:
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=247423477&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software
Where 247423477 is your 9 digit app ID (the main difference is you have to append &onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software after the app ID).
All the answers above have now been deprecated (iOS 7, but may work) thus, I provide the new way Apple recommends to provide links to the Apps.
The link for your App is the one from iTunes (use Copy Link), this one is recommended for use in code:
Swift 3.0
let path = URL(string: "https://itunes.apple.com/us/app/calcfast/id876781417?mt=8")
UIApplication.shared.open(path!)
Or better -- treat the optional correctly and handle the possibility of not being able to reach the link:
if let path = URL(string: "https://itunes.apple.com/us/app/calcfast/id876781417?mt=8") {
UIApplication.shared.open(path) {
(didOpen:Bool) in
if !didOpen {
print("Error opening:\(path.absoluteString)")
}
}
}
Objective-C
#define APP_URL_STRING #"https://itunes.apple.com/us/app/calcfast/id876781417?mt=8"
then you can call APP_URL_STRING in your code:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: APP_URL_STRING] options:#{} completionHandler:nil];
Note, that this is the recommended way now by Apple, as the previous method of processing redirect links has been deprecated and are not supported.
The link for all your Apps, if you have more than one:
#define MYCOMPANY_URL_PATH #"http://appstore.com/mycompany"
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: MYCOMPANY_URL_PATH] options:#{} completionHandler:nil];
The App link above is recommended for use in code or links that are not seen directly by the user. If you want to provide link that may be seen and remembered by the user then use the following:
http://appstore.com/calcfast
Using this URL was the perfect solution for me. It takes the user directly to the Write a Review section. Credits to #Joseph Duffy.
For a sample code try this :
Swift 3, Xcode 8.2.1 :
let openAppStoreForRating = "itms-apps://itunes.apple.com/gb/app/id1136613532?action=write-review&mt=8"
if UIApplication.shared.canOpenURL(URL(string: openAppStoreForRating)!) {
UIApplication.shared.openURL(URL(string: openAppStoreForRating)!)
} else {
showAlert(title: "Cannot open AppStore",message: "Please select our app from the AppStore and write a review for us. Thanks!!")
}
Here showAlert is a custom function for an UIAlertController.
I have this to get the Product ID automatically and generate App Store Review and Product page links.
- (void) getAppStoreLinks {
productID = [[NSUserDefaults standardUserDefaults] objectForKey:#"productID"]; //NSNumber instance variable
appStoreReviewLink = [[NSUserDefaults standardUserDefaults] objectForKey:#"appStoreReviewLink"]; //NSString instance variable
appStoreLink = [[NSUserDefaults standardUserDefaults] objectForKey:#"appStoreLink"]; //NSString instance variable
if (!productID || !appStoreReviewLink || !appStoreLink) {
NSString *iTunesServiceURL = [NSString stringWithFormat:#"https://itunes.apple.com/lookup?bundleId=%#", [NSBundle mainBundle].bundleIdentifier];
NSURLSession *sharedSes = [NSURLSession sharedSession];
[[sharedSes dataTaskWithURL:[NSURL URLWithString:iTunesServiceURL]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
if (data && statusCode == 200) {
id json = [[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions)0 error:nil][#"results"] lastObject];
//productID should be NSNumber but integerValue also work with NSString
productID = json[#"trackId"];
if (productID) {
appStoreReviewLink = [NSString stringWithFormat:#"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%d&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8",productID.integerValue];
appStoreLink = [NSString stringWithFormat:#"itms-apps://itunes.apple.com/app/id%d",productID.integerValue];
[[NSUserDefaults standardUserDefaults] setObject:productID forKey:#"productID"];
[[NSUserDefaults standardUserDefaults] setObject:appStoreReviewLink forKey:#"appStoreReviewLink"];
[[NSUserDefaults standardUserDefaults] setObject:appStoreLink forKey:#"appStoreLink"];
}
} else if (statusCode >= 400) {
NSLog(#"Error:%#",error.description);
}
}
] resume];
}
}
Open app's Review Page
- (IBAction) rateButton: (id)sender {
NSString *appStoreReviewLink = appStoreReviewLink;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreReviewLink]];
}
Open app's App Store page
- (IBAction) openAppPageButton: (id)sender {
NSString *appStoreLink = appStoreLink;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: appStoreLink]];
}
It is said that this bug will be fixed on iOS7.1. Read here on the corona forum, and here on the iPhoneDevSDK.

Facebook Prompt automatically disappearing on iOS 7

I am working with Share kit for Facebook sharing. and using action sheet to open a Facebook popup. Its working fine on iOS 6 or previous version.
But in iOS 7 its automatically disappeared on action sheet button click.
Please guide me.
Thanks
Find the method -(void)showWebView in FBDialog.m (around line 410).
Replace this code
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
With this
if (window.windowLevel != UIWindowLevelNormal) {
for(window in [UIApplication sharedApplication].windows) {
if (window.windowLevel == UIWindowLevelNormal)
break;
}
}
I've tested it on iOS7 and iOS6, it works.
Have a nice day :)

How can I get UIWebView to open Facebook login page in response to the OAuth request on iOS 5 and iOS 6?

We have:
(1) Facebook API-based web application with Facebook OAuth functionality (“the FB web app”)
(2) UIWebView-based browser on iPad (“the Browser”)
Our objective is to open the Facebook Login page to sign in to the FB web app (1) inside the UIWebView-based Browser (2) on iPad.
There is a somewhat similar issue here:
http://facebook.stackoverflow.com/questions/11337285/no-longer-able-to-login-to-ios-app-via-oauth-the-page-requested-was-not-found
However, the issue of that question happens after the user enters login and password into the Facebook form. Our problem is that we cannot get the Facebook login form displayed in the first place. Changing the app type to from “Web” to “Native/Desktop”, as suggested in that question, did not help.
Steps:
1. Open our web page (simple HTML page) with this UIWebView Browser
2. Click on “FB web app” launch button on this page
3. OnClick JavaScript tries to initiate OAuth, which should open the login screen of Facebook to sign in to the FB web app
Current outcome (issue):
On iOS 5.+ and iOS 6.+ devices
- Our web page stays unchanged
- Facebook login page is NOT shown (our web page is still displayed)
On iOS 4.3 (works as expected):
- the Facebook login page is opened in the same UIWebView object of the Browser (replaces our web page)
Expected outcome:
- Facebook login page is displayed, and the user can enter Facebook login & password
- Works on iOS 5.+ and iOS 6.+ if launched in Safari browser on iPad. Facebook login page is opened in a separate tab (in contrast, there are no separate tabs in UIWebView)
Question: How can I get UIWebView to open Facebook login page in response to the OAuth request on iOS 5+ and iOS 6+?
More technical details:
We log different NSURLRequest fields from within
-(BOOL)webView(UIWebView*)webView shouldStartLoadWithRequest(NSURLREquest*)request navigationType:…
And we notice some difference in logs for “correct” and “incorrect” behaviors. Here how execution flows look for me:
Firstly, I press “FB Web App” launch button to initiate OAuth, then some cases go
iOS 4.3, “correct”
request to www.facebook.com/dialog/oauth?...
request to fbwebapp.com
request to m.facebook.com/login.php?....
--here facebook login appears
iOS 5.0, “incorrect1”
request to www.facebook.com/dialog/oauth?...
request to fbwebapp.com
request to m.facebook.com/login.php?...
Then it may be
--a lot of m.facebook.com/login.php?...with next… in parameters
followed by sqlite error
--right now I see “Sorry, something went wrong” page from facebook (it’s a first time at all I encounter it)
iOS 6.0 “incorrect2”
request to www.facebook.com/dialog/oauth?...
request to fbwebapp.com
-(void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error is invoked with error code -999
You can see that behavior definitely depends on iOS version. But common case is that error happens on the step of obtaining m.facebook.com/login.php.. URL. But that’s all that we can detect.
We’re banging our heads against that wall for the whole day looking for solutions. Hopelessly.
Can you help us get the Facebook Login page opened in the UIWebView in response to OAuth?
just use : this code
if (![FBSDKAccessToken currentAccessToken])
{
FBSDKLoginManager *manager = [[FBSDKLoginManager alloc]init];
manager.loginBehavior = FBSDKLoginBehaviorWeb;
[manager logInWithReadPermissions:#[#"public_profile", #"email", #"user_friends"] handler:
^(FBSDKLoginManagerLoginResult *result, NSError *error) {
NSLog(#"result.token: %#",result.token.tokenString);
NSLog(#"%#",result.token.userID);
NSLog(#"%hhd",result.isCancelled);
}];
}
// here manager.loginBehavior = FBSDKLoginBehaviorWeb; is all you need to open facebook in UIWebview
Did it!
It kinda of a hack, but the js facebook sdk login on UiWebView at iOS 6 finally works.
How it could be done? It is a pure JS + Facebook JS SDK + UIWebView Delegate handling functions solution.
JS - First step)
a login button (to connect with facebook) calls this function example, that will trigger Face JS login/oauth dialogs:
function loginWithFacebookClick(){
FB.login(function(response){
//normal browsers callback
});
}
JS - Second step)
add a authResponseChange listener every time user loads the webpage ( after FB.init() ) to catch user's connected status:
FB.Event.subscribe('auth.authResponse.Change', function(response){
//UIWebView login 'callback' handler
var auth = response.authResponse;
if(auth.status == 'connected'){
//user is connected with facebook! just log him at your webapp
}
});
AND with app's UIWebView delegate functions you can handler facebook oauth responses
Objective C - Third step)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url = [[request URL] absoluteString];
//when user status == connected (has a access_token at facebook oauth response)
if([url hasPrefix:#"https://m.facebook.com/dialog/oauth"] && [url rangeOfString:#"access_token="].location != NSNotFound)
{
[self backToLastPage];
return NO;
}
return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *url = [[webView.request URL] absoluteString];
if([url hasPrefix:#"https://m.facebook.com/dialog/oauth"])
{
NSString *bodyHTML = [webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
//Facebook oauth response dead end: is a blank body and a head with a script that does
//nothing. But if you got back to your last page, the handler of authResponseChange
//will catch a connected status if user did his login and auth app
if([bodyHTML isEqualToString:#""])
{
[self backToLastPage];
}
}
}
So, when 'redirect' user to the last loaded page, the second step is going to handler user action at facebook login dialogs.
If I got too fast with this answer, please ask me!
Hope it helps.
In case anyone is googling, here's what worked for me:
-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)inType {
if ([request.URL.absoluteString containsString:#"m.facebook.com"]) {
if ([request.URL.absoluteString rangeOfString:#"back"].location == 0) {
[self.popUp removeFromSuperview];
self.popUp = nil;
return NO;
}
if (self.popUp) {
return YES;
}
UIWebView *wv = [self popUpWebView];
[wv loadRequest:request];
return NO;
}
return YES;
}
- (UIWebView *) popUpWebView {
toolbar height
UIWebView *webView = [[UIWebView alloc]
initWithFrame:CGRectMake(0, 0, (float)self.view.bounds.size.width,
(float)self.view.bounds.size.height)];
webView.scalesPageToFit = YES;
webView.delegate = self;
// Add to windows array and make active window
self.popUp = webView;
[self.view addSubview:webView];
return webView;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (self.popUp) {
NSError *error = nil;
NSString *jsFromFile = #"window.close=function(){window.location.assign('back://' + window.location);};";
__unused NSString *jsOverrides = [webView
stringByEvaluatingJavaScriptFromString:jsFromFile];
JSContext *openerContext = [self.webView
valueForKeyPath:#"documentView.webView.mainFrame.javaScriptContext"];
JSContext *popupContext = [webView
valueForKeyPath:#"documentView.webView.mainFrame.javaScriptContext"];
popupContext[#"window"][#"opener"] = openerContext[#"window"];
}
//this is the secret sauce
if (webView == self.popUp
&& [webView.request.URL.absoluteString containsString:#"m.facebook.com"]
&& [[webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"] isEqualToString:#""]) {
[webView stringByEvaluatingJavaScriptFromString:#"eval(document.getElementsByTagName('script')[0].text)"];
}
}
I snagged a bunch of this implementation from here.
Depending on your web implementation, there will likely be one extra step. The Facebook script actually executes a window.close() then a window.open() then a window.close(). For me this was causing problems because on the web side, after this login is complete, my window (i.e. for the webView that I want the user to log in to) was getting a window.close() call, coming from the Facebook SDK. I'm assuming this is because the Facebook SDK expects that window.open() call to open a new window that it will close.
Since we didn't override the functionality of window.open(), calling window.open() won't do anything, and the Facebook SDK will attempt to close your window. This could cause all kind of problems, but for me since I'm using Parse, window.localStorage was set to null so I was getting all kinds of errors.
If something like this is happening for you, you have two options to fix it:
If you have control of the web code, and your down for a small hack, throw this in window.close=function(){}
If you don't have control of the web code, you can either add an override to window.close for the main webView like we did for the popUp webView, or override the window.open function to open another popUp (which is described in more detail here)
Use the FBDialog class to prompt the user to login. This uses a webview inside of the app, therefore on successful login the user will be logged in inside of any UIWebView:
NSString *kRedirectURL = #"fbconnect://success";
NSString *kSDK = #"ios" ;
NSString *kLogin = #"oauth";
NSString *kDialogBaseURL = #"https://m.facebook.com/dialog/";
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
AE_FACEBOOK_APPID, #"client_id",
#"user_agent", #"type",
kRedirectURL, #"redirect_uri",
#"touch", #"display",
kSDK, #"sdk",
nil];
NSString *loginDialogURL = [kDialogBaseURL stringByAppendingString:kLogin];
FBLoginDialog* loginDialog = [[FBLoginDialog alloc] initWithURL:loginDialogURL
loginParams:params
delegate:self];
[loginDialog show];
Then make your class adhere to the FBDialogDelegate protocol, and add this function to your class:
-(void)fbDialogLogin: (NSString *)token expirationDate:(NSDate *)expirationDate{
// Store the token and expiration date into the FB SDK
self.facebook.accessToken = token;
self.facebook.expirationDate = expirationDate;
// Then persist these so the SDK picks them up on next load
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.facebook.accessToken forKey:ACCESS_TOKEN_KEY];
[defaults setObject:self.facebook.expirationDate forKey:EXPIRATION_DATE_KEY];
[defaults synchronize];
}
HTH!
How to facebook login in UIWebView.
Objective-c
Use taylorstine's answer.
He saved my day. Thank you taylorstine
But I'm using Swift 3. so I just converted code below from taylorstine's answer.
Swift 3.
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let _ = request.url?.absoluteString.range(of: "m.facebook.com" ) {
if let _ = request.url?.absoluteString.range(of: "back"){
self.popUp?.removeFromSuperview()
self.popUp = nil
return false
}
if let _ = self.popUp {
return true
}
let wv = popUpWebView()
wv.loadRequest(request)
return false
}
return true
}
func popUpWebView() -> UIWebView {
let webView = UIWebView(frame: self.view.frame)
webView.delegate = self
self.popUp = webView
self.view.addSubview(webView)
return webView
}
func webViewDidFinishLoad(_ webView: UIWebView) {
if let _ = self.popUp {
let jsFromFile = "window.close=function(){window.location.assign('back://' + window.location);};"
let _ = webView.stringByEvaluatingJavaScript(from: jsFromFile)
let openerContext = self.webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
let popupContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
popupContext.setObject("opener", forKeyedSubscript: "window" as (NSCopying & NSObjectProtocol)!)
popupContext.setObject(openerContext.objectForKeyedSubscript("window"), forKeyedSubscript: "opener" as (NSCopying & NSObjectProtocol)!)
}
if webView == self.popUp
&& (webView.request?.url?.absoluteString.range(of:"m.facebook.com") != nil)
&& webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML") == "" {
webView.stringByEvaluatingJavaScript(from: "eval(document.getElementsByTagName('script')[0].text)")
}
}

What will happen to users running a lower version of IOS if new code is called?

I am fairly new to iOS Development and I've always wondered if a user running my application on iOS 4 were to try and run this code:
//POST TWEET//
- (void)showTweetSheet
{
TWTweetComposeViewController *tweetSheet =
[[TWTweetComposeViewController alloc] init];
tweetSheet.completionHandler = ^(TWTweetComposeViewControllerResult result) {
switch(result) {
case TWTweetComposeViewControllerResultCancelled:
break;
case TWTweetComposeViewControllerResultDone:
break;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:YES completion:^{
NSLog(#"Tweet Sheet has been dismissed.");
}];
});
};
[tweetSheet setInitialText:#"Check out this cool picture I found on #Pickr_"];
// Add an URL to the Tweet. You can add multiple URLs.
if (![tweetSheet addURL:[NSURL URLWithString:ImageHost]]){
NSLog(#"Unable to add the URL!");
}
[self presentViewController:tweetSheet animated:YES completion:^{
NSLog(#"Tweet sheet has been presented.");
}];
}
What would happen? Would the application just terminate with an error or will the code just not run? And how do I properly implement features that are OS specific? Would I just use something like this:
NSString *DeviceVersion = [[UIDevice currentDevice] systemVersion];
int DeviceVersionInt = [DeviceVersion intValue];
if (DeviceVersionInt > 5)
{
//do something.
}
else
{
//don't do a thing.
}
It will crash on iOS 4 if you write iOS5 features without checking if they are available or not. Try to implement Twitter like this
Class twClass = NSClassFromString(#"TWTweetComposeViewController");
if (!twClass) // Framework not available, older iOS
{
//use iOS4 SDK to implement Twitter framework
}
else {
//use Apple provided default Twitter framework
}
Make sure you have added Twitter Framework with weak link.
Id imagine that it would work the same as with any other api. If you link against a function which is not in a previous version, the program will crash on an attempt to call the function. Therefore, version switches are used, as you demonstrated, to avoid crashes.
The app would crash. If you want to implement features based on iOS, you can use a variety of methods. See this question.

Simple iPhone image viewer howto

I need to develop simple image viewer, much like the default iPhone Photos application, but for images located on remote server. I don't have any point where to start as I don't have any experience yet with such task (how to make a slideshow and how to handle animations when user slides photos with his finger etc.)
Can you please point me to some source - docs, howtos or sample project of such a kind?
I recommend you start with Joe Hewitt's three20 library (introductory text here). In the TTCatalog sample app, you will find a photo browser and three20 has been designed to easily use photos from remote servers.
Try this one https://github.com/mwaterfall/MWPhotoBrowser
Visit http://www.raywenderlich.com/1845/how-to-create-a-simple-iphone-app-tutorial-part-2
Might I recommend Titanium from Appcelerator? I have worked in both xcode and titanium and for quick and dirty projects, titanium might work. Lots of demos out there.
Here's my implementation:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
self.startX = scrollView.contentOffset.x;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
//NSLog(#"scrollViewDidEndDragging");
self.endX = scrollView.contentOffset.x;
self.photoIdx = (int)self.startX / Normalize(1160);
if (decelerate == FALSE)
{
int intoThePhoto = (int)self.photoScrollView.contentOffset.x % Normalize(1160);
if (intoThePhoto < Normalize(1060/2))
[scrollView setContentOffset:CGPointMake(Normalize(1160)*self.photoIdx,0) animated:YES];
else
[scrollView setContentOffset:CGPointMake(Normalize(1160)*(self.photoIdx+1),0) animated:YES];
}
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
if ((self.endX - self.startX) > 0 && self.photoIdx < ([self.photos count] -1))
[scrollView setContentOffset:CGPointMake(Normalize(1160)*(self.photoIdx+1),0) animated:YES];
else if ((self.endX - self.startX) < 0 && self.photoIdx != 0)
[scrollView setContentOffset:CGPointMake(Normalize(1160)*(self.photoIdx-1),0) animated:YES];
}