Instagram IOS API Implementation - ios

I am trying to get the authentication token to be able to grab a user's info. I registered my app in the instagram api page and everything seems to work except that I am not able to retrieve an authentication token or anything information. (I think it might be because of the redirect url i just made a dummy url) I can login to my instagram account and authorize my app to retrieve information but I dont get anything printed on my console so Im assuming im not being able to retrieve anything.
the code:
import UIKit
import WebKit
class ViewController3: UIViewController, UIWebViewDelegate {
#IBOutlet weak var WebView1: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let authURL = String(format: "%#?client_id=%#&redirect_uri=%#&response_type=token&scope=%#&DEBUG=True", arguments: [API.INSTAGRAM_AUTHURL,API.INSTAGRAM_CLIENT_ID,API.INSTAGRAM_REDIRECT_URI, API.INSTAGRAM_SCOPE])
let urlRequest = URLRequest.init(url: URL.init(string: authURL)!)
WebView1.load(urlRequest)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var tts = segue.destination as! Manage_Ad_VC
tts.S_Media_R = "Instagram"
}
func WebView1(_ WebView1: UIWebView, shouldStartLoadWith request:URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
return checkRequestForCallbackURL(request: request)
}
func checkRequestForCallbackURL(request: URLRequest) -> Bool {
print("Instagram authentication token ==")
let requestURLString = (request.url?.absoluteString)! as String
if requestURLString.hasPrefix(API.INSTAGRAM_REDIRECT_URI) {
let range: Range<String.Index> = requestURLString.range(of: "#access_token=")!
handleAuth(authToken: requestURLString.substring(from: range.upperBound))
return false;
}
return true
}
func handleAuth(authToken: String) {
print("Instagram authentication token ==", authToken)
}
}
struct API {
static let INSTAGRAM_AUTHURL = "https://api.instagram.com/oauth/authorize/"
static let INSTAGRAM_CLIENT_ID = "myclientidgoeshere"
static let INSTAGRAM_CLIENTSERCRET = " myclientsercretgoeshere "
static let INSTAGRAM_REDIRECT_URI = "http://www.dummyurl.com/just_a_made_up_dummy_url"
static let INSTAGRAM_ACCESS_TOKEN = ""
static let INSTAGRAM_SCOPE = "follower_list+public_content" /* add whatever scope you need https://www.instagram.com/developer/authorization/ */
}
enter image description here

U have used WKWebView and UIWebViewDelegate. It is not WKWebView delegate. This view has been inherited from UIView - not from uiwebview - that's why delegates methods does not work. Try to use WKNavigationDelegate with its methods.

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.url, url.host == "URL FOR OAUTH GOES HERE" {
if url.absoluteString.range(of: "access_token") != nil {
let urlParts = url.absoluteString.components(separatedBy: "=")
let code = urlParts[1]
let userInfoURL = "https://api.instagram.com/v1/users/self/?access_token=" + code
//Make request with the userInfoURL to retrieve the user Info.
}
}
return true
}

We need "Access token" to go further.But it seems empty in your case.Try to run local server either through node/jupiter/MAMP or anything and check your localhost page is popping up.
Once your localhost is up and running.Please paste the below link in the browser by replacing the client_id to yours.
https://www.instagram.com/oauth/authorize/?client_id=Your_Client_Id&redirect_uri=http://localhost:8000&response_type=token&scope=public_content
Make sure you are giving the same redirect uri while you registered.
Please follow this link for further clarification
Click on Authorize in the page to be displayed in the browser.And check the URL in the browser, your access token would be passed for the next page.Copy this token and use it in the code

Related

Dailymotion Player is not Working in UIWebview Swift 3

I've written the following code in Xcode 9. The ID variable comes from another viewcontroller of mine, via a segue.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ID" {
if let indexPath = self.tblview.indexPathForSelectedRow {
let controller = segue.destination as! DViewController
let value = arrRes[indexPath.row]
controller.videoId = value["id"] as! String
}
}
class DViewController : UIViewController {
#IBOutlet weak var Views: UIWebView!
var ID : String!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.dailymotion.com/embed/video/\(ID)?sharing-enable=0&ui-logo=0&endscreen-enable=0&autoplay=1")
Views.loadRequest(URLRequest(url: url!))
Views.allowsInlineMediaPlayback = true
}
}
}
When I run the code, I get the following error:
Page not found. The page you're looking for is ... restricted ...
You're getting that error because the page isn't found. Try going to that page in a browser. The link you put in your code returns a 404 page, in other words, it does not go anywhere meaningful. Your code looks fine; it's the link that is broken.
Before you start trying to debug your code, try to think of the simplest possible explanation of why it might not be working. Usually the simplest explanation is the correct explanation. In this case, the error message said it all - the page couldn't be found. There's nothing there.

Swift: How do unit test UIWebView loading?

My app has a basic webview controller to perform some operations. This view in the storyboard is not much besides a wrapper around a UIWebView. The controller itself has various public functions that can be called to load pages in the webview, like so:
class WebViewController: UIViewController, UIWebViewDelegate {
// MARK: Properties
#IBOutlet var webView: UIWebView!
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
loadHomePage()
}
// MARK: Public
public func loadHomePage() {
navigateWebView(to: HOME_PAGE)
}
public func loadSettingsPage() {
navigateWebView(to: SETTINGS_PAGE)
}
public func loadSignOutPage() {
navigateWebView(to: SIGN_OUT_PAGE)
}
// MARK: Private
private func navigateWebView(to url: String) {
let request = URLRequest(url: URL(string: url)!)
webView.loadRequest(request)
}
I'm trying to write unit tests that verify that the proper URL is sent to the loadRequest function of the webview. Note that I don't actually care about loading the URL; this is just a unit test, so all I really want to test is that loadSettingsPage sends a URLRequest with the SETTINGS_PAGE URL to the webview to load, for example.
I tried something like this, with no success:
_ = webViewController.view // Calls viewDidLoad()
XCTAssertEqual(webViewController.webView.request?.url?.absoluteString, HOME_PAGE)
The value of the first part of the assertEqual was nil.
I assume I need to mock out the webView somehow but I'm not sure how to go about that. Any suggestions?
As a follow-up, I'd also like to be able to test when things like webView.reload() and webview.goBack() are called, so any pointers there would be appreciated as well. Thanks!

Check if URL has changed in WebView?

I'm trying to check if the URL has changed in the webView. For example if I were to initially load a page like a Wordpress Sign In page, and I wanted to know when it changed and got redirected to the login page. I tried using this resource enter link description here but the answer seems to be incomplete and does not work.
func validateUrl (stringURL : NSString) -> Bool {
var urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
let predicate = NSPredicate(format:"SELF MATCHES %#", argumentArray:[urlRegEx])
var urlTest = NSPredicate.predicateWithSubstitutionVariables(predicate)
return predicate.evaluateWithObject(stringURL)
}
urlTest is never called so i'm not sure the purpose of it.
if (validateUrl(stringURL: "http://google.com")) {
//will return true
print("Do Stuff");
}
else {
print("OTHER STUFf")
//If it is false then do stuff here.
}
And then to call this function
func webView(WebViewNews: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
if (validateUrl(request.URL().absoluteString())) {
//if will return true
print("Do Stuff");
}
}
I added a return function at the end of my code, but the example does not include a return. I have very little experience in Webview, so any advice or help would be appreciated.
Use the webViewDidFinishLoad function of the UIWebViewDelegate to get the current URL loaded in your webview. Everytime the webview loads a URL the function webViewDidFinishLoad is called.
class YourClass: UIViewController, UIWebViewDelegate {
let initialURL = URL(string: "https://www.google.com.pe/")
#IBOutlet weak var webView:UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.loadRequest( URLRequest(url: initialURL) )
}
func webViewDidFinishLoad(_ webView: UIWebView) {
if webView.request != URLRequest(url: initialURL!) {
//DO YOUR STUFF HERE
}
}
}

Xcode Opening a WebView in another ViewController

I'm trying to make an app with a button which launch a webview.
I've followed many tutorial and read differents topic about the subject but I cant get it working : I'm getting this message when I test my code :
"Cannot call value of non-function type UIWebView!"
Here's the steps I did until now
Adding a button in the principal view Controller
Creating an another view Controller named 'WebViewController'
Adding a segue to link the button to WebViewController
Creating a new Cocoa Touch Class file 'WebViewController'
Setting the WebViewController custom class with the WebViewController class
Adding a webView in the WebViewController ViewController named 'myWebView'
Here's the WebViewController class (in which I got the error when I run the project)
import UIKit
class WebViewController: UIViewController{
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//define url
let url = NSURL (string: "http://www.my-url.com")
//request
let req = NSURLRequest(url: url as! URL)
//load request into the webview
myWebview(req as URLRequest) //error happens here :
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Here's a screenshot (picture talks more than long text, right =)
Thanks !
You can use SFSafariViewController:
import SafariServices
let url = URL(string: "https://www.google.com")
let safariVC: SFSafariViewController = SFSafariViewController(url: url)
self.present(safariVC, animated: true, completion: nil)
I used swift 3 syntax.
That code opens a Safari Web view and you dont need to create segues and view controlles in storyboard.
Try to use:
let url = NSURL (string: "https://google.com")
let request = NSURLRequest(url: url as! URL)
self. myWebView.loadRequest(request as URLRequest)
This code works for me

Attempting to load Webview with PDF, receiving link from Parse

I am attempting to load a lunch menu PDF into a web view for a high school app that I am updating. Currently, it can load a PDF into the web view and display it just fine, but I want to speed up the monthly update process by having my app receive the link through Parse (Which I can update much quicker than updating the link in the app itself with Apple's 7 day review period), and then load the PDF. Currently, with what I have put together, my app will not load the PDF. Here's the entire view:
import UIKit
class AlaCarte_ViewController: UIViewController {
#IBOutlet weak var webviewAlaCarte: UIWebView!
var urlpath = String()
func loadAddressUrl(){
let requestURL = NSURL (string:urlpath)
let request = NSURLRequest(URL: requestURL!)
webviewAlaCarte.loadRequest(request)
alaCarteUpdate()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
clearPDFBackground(self.webviewAlaCarte)
}
func clearPDFBackground(webView: UIWebView) {
var view :UIView?
view = webView as UIView
while view != nil {
if NSStringFromClass(view?.dynamicType) == "UIWebPDFView" {
view?.backgroundColor = UIColor.clearColor()
}
view = view?.subviews.first as! UIView?
}
}
func alaCarteUpdate() {
var query = PFQuery(className: "AlaCarte")
query.getObjectInBackgroundWithId("rT7MpEFySU") {(AlaCarte: PFObject!, error: NSError!)-> Void in
if error == nil && AlaCarte != nil {
println(AlaCarte)
} else {
println(error)
}
let AlaCarteLink = AlaCarte["webaddress"] as! String
self.urlpath = AlaCarteLink
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadAddressUrl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
The link is stored in my Parse app as "webaddress" and does not contain end quotations. Adding them does not help. Any ideas?
It looks to me like you're not telling the web view to load the URL once it's retrieved from Parse.
Try adding the following lines after self.urlpath = AlaCarteLink in alaCarteUpdate().
let requestURL = NSURL (string:self.urlpath)
let request = NSURLRequest(URL: requestURL!)
self.webviewAlaCarte.loadRequest(request)
I think it would also be a good idea to add a function that specifically loads a url string into your web view, so you can call it from both inside alaCarteUpdate(), and loadAddressUrl(), and avoid the duplicate 3x lines. I've assumed that you're loading the URL in loadAddressURL() so that you can show a local/cached document while retrieving the latest from Parse.

Resources