Coder Social home page Coder Social logo

marty-suzuki / urlembeddedview Goto Github PK

View Code? Open in Web Editor NEW
648.0 23.0 72.0 7.66 MB

URLEmbeddedView automatically caches the object that is confirmed the Open Graph Protocol.

License: MIT License

Ruby 1.37% Swift 96.29% Objective-C 2.24% C 0.09%
ogp embedded url thumbnail swift carthage cocoapods ios tvos

urlembeddedview's Introduction

URLEmbeddedView

Platform Language Carthage compatible Version License

Features

  • Simple interface for fetching Open Graph Data
  • Be able to display Open Graph Data
  • Automatically caching Open Graph Data
  • Automatically caching Open Graph Image
  • Tap handleable
  • Clearable image cache
  • Clearable data cache
  • Support Swift3.2 (until 0.11.x)
  • Supprot Swift4.x (until 0.17.1)
  • Support Swift5 (since 0.18.0)
  • Support Carthage since 0.11.1
  • Support tvOS since 0.16.0
  • Custom implementation of OGData cache

Usage

To run the example project, clone the repo, and run carthage update from the Example directory first.

let embeddedView = URLEmbeddedView()
embeddedView.loadURL(urlString)

Layouts

  • Default

  • No Image

  • No response

Customization

embeddedView.textProvider[.Title].font = .boldSystemFontOfSize(18)
embeddedView.textProvider[.Title].fontColor = .lightGrayColor()
embeddedView.textProvider[.Title].numberOfLines = 2
//You can use ".Title", ".Description", ".Domain" and ".NoDataTitle"

Data and Image Cache

You can get Open Graph Data with OGDataProvider.

OGDataProvider.shared.fetchOGData(urlString: String, completion: ((OpenGraph.Data, Error?) -> Void)? = nil) -> String?
OGDataProvider.shared.deleteOGData(urlString: String, completion: ((Error?) -> Void)? = nil)
OGDataProvider.shared.deleteOGData(_ ogData: OpenGraph.Data, completion: ((Error?) -> Void)? = nil)

You can configure time interval for next updating of OGData. Default is 10 days.

OGDataProvider.shared.updateInterval = 10.days

You can get UIImage with OGImageProvider.

OGImageProvider.shared.loadImage(urlString: String, completion: ((UIImage?, Error?) -> Void)? = nil) -> NSURLSessionDataTask?
OGImageProvider.shared.clearMemoryCache()
OGImageProvider.shared.clearAllCache()

Custom Data Cache implementation

Default cache feature is using Core Data. If you want to use other cache features, please implement cache manager with OGDataCacheManagerProtocol. For example, URLEmbeddedView has OGDataNoCacheManager that feature is not using cache. If you want to use that feature, you can use like this.

OGDataProvider.shared.cacheManager = OGDataNoCacheManager()

You can implement custom cache feature and use it like this.

class MemoryCacheManager: OGDataCacheManagerProtocol {
    // implementation of required methods
}

OGDataProvider.shared.cacheManager = MemoryCacheManager()

OpenGraph.Data Properties

public let imageUrl: URL?
public let pageDescription: String?
public let pageTitle: String?
public let pageType: String?
public let siteName: String?
public let sourceUrl: URL?
public let url: URL?

OpenGraphDataDownloader

You can only use download feature of OGData with OpenGraphDataDownloader like this.

let urlString = ...
OpenGraphDataDownloader.shared.fetchOGData(urlString: urlString) { result in
    switch result {
    case let .success(data, isExpired):
        // do something
    case let .failure(error, isExpired):
        // do something
    }
}

If you use OGDataProvider with OGDataNoCacheManager, it is almost same process.

OGDataProvider.shared.cacheManager = OGDataNoCacheManager()
let urlString = ...
OGDataProvider.shared.fetchOGData(urlString: urlString) { ogData, error in
    // do something
}

Installation

CocoaPods

URLEmbeddedView is available through CocoaPods. To install it, simply add the following line to your Podfile:

# Uncomment the next line to define a global platform for your project
# platform :ios, '8.0'

target 'Your Project Name' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for URLEmbeddedViewSample
  pod "URLEmbeddedView"
end

Carthage

If you’re using Carthage, simply add NoticeObserveKit to your Cartfile:

github "marty-suzuki/URLEmbeddedView"

Use in Objective-C

#import <URLEmbeddedView/URLEmbeddedView-Swift.h>

- (void)viewDidLoad {
    [super viewDidLoad];
    URLEmbeddedView *embeddedView = [[URLEmbeddedView alloc] init];
    [self.view addSubView:embeddedView];
    [embeddedView loadURL:@"https://github.com/" completion:nil];
}

- (void)setUpdateInterval {
  [OGDataProvider sharedInstance].updateInterval = [NSNumber days:10];
}

- (void)fetchOpenGraphData {
  [[OGDataProvider sharedInstance] fetchOGDataWithUrlString:self.textView.text
                                            completion:^(OpenGraphData *data, NSError *error) {
      NSLog(@"OpenGraphData = %@", data);
  }];
}

Here is Objective-C sample.

Special Thanks

Requirements

  • Xcode 10.2 or greater
  • iOS 8.0 or greater
  • tvOS 10.0 or greater
  • UIKit
  • CoreData
  • CoreGraphics

Other

Author

Taiki Suzuki, [email protected]

License

URLEmbeddedView is available under the MIT license. See the LICENSE file for more info.

urlembeddedview's People

Contributors

gabrielpawscout avatar marty-suzuki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

urlembeddedview's Issues

Swift 3.0 Support

Good morning. I am using your library in my project (through pods), and it's really great. But with xcode 8, it's not building anymore :( Could u fix it pls, I need it very much

Show view only if there's a response

there's any way to just show the view if there's a response? Or even a response with just the image.

It would be nice to return on the completion block the type of layout that's going to be shown so the dev can choose to show it or not

Carthage Installation in Objective-C Project - Steps

Since the last time I installed the repository and removed it, I cannot get it to install again. I have the Summy.swift file created. Do you happen to have all of the steps needed to embed the project in an Objective-C app, hopefully via Carthage, handy? I am not sure how I ended up getting it installed last time, but I have been trying and cannot get it in this time without getting this error on 'Run':

yld: Library not loaded: @rpath/libswiftSwiftOnoneSupport.dylib
Referenced from: /Users/home/Library/Developer/Xcode/DerivedData/Build/Products/Debug-iphonesimulator/URLEmbeddedView.framework/URLEmbeddedView
Reason: image not found
(lldb)

I know I'm an idiot for not being able to figure this out, but if you have the steps handy that would be helpful. Thanks. : )

Value of type 'Any' has no member '1'

In two places, I get this error.Both are in the AutoLayout.swift file.

  `func addConstraints(with view: UIView,
                    size: Size,
                    relatedBy relation: NSLayoutRelation = .equal,
                    multiplier: CGFloat = 1) {
    view.translatesAutoresizingMaskIntoConstraints = false
    addConstraints([
            (.width, size.width),
            (.height, size.height)
        ]
        .flatMap { value in
            value.1.map {
                .init(item: view,
                      attribute: value.0,
                      relatedBy: relation,
                      toItem: nil,
                      attribute: .notAnAttribute,
                      multiplier: multiplier,
                      constant: $0)
            }
        }
    )
}`

  `func addConstraints(with view: UIView, edges: Edges, multiplier: CGFloat = 1) {
    view.translatesAutoresizingMaskIntoConstraints = false
    addConstraints([
            (.top, edges.top),
            (.left, edges.left),
            (.right, edges.right),
            (.bottom, edges.bottom)
        ]
        .flatMap { value in
            value.1.map {
                .init(item: view,
                      attribute: value.0,
                      relatedBy: .equal,
                      toItem: self,
                      attribute: value.0,
                      multiplier: multiplier,
                      constant: $0)
            }
        })
}`

Along with a bunch of warnings:

screenshot 2018-06-21 at 2 17 07 pm

Install without Core Data?

Hi Marty! I understand that there is no way to cache without Core Data, and I can't include another Core Data database in my app at this time, so I am planning on using 'fetch the info' only. Is there any way to install URLEmbeddedView without the repository creating a Core Data store at all? Like 'URLEmbeddedView Light'? : )

Customize View

Hello. Are you planning on creating a nib for the embedded view? This would make the auto layout much more simple - and customizable!

Related to issue number #39

Hi, Suzuki Sorry to bother you again, How can I update to the specific version of the pod you specified in that bug number #39.
I tried updating to the latest version (0.12.0).
But it won't help for me because I'm using 8.3.3 and the pod is upgraded for Swift 4

Value of type '[(_, CGFloat?)]' has no member 'compactMap'

func addConstraints(with view: UIView,
size: Size,
relatedBy relation: NSLayoutRelation = .equal,
multiplier: CGFloat = 1) {
view.translatesAutoresizingMaskIntoConstraints = false
addConstraints([
(.width, size.width),
(.height, size.height)
]
.compactMap { (value: (NSLayoutAttribute, CGFloat?)) in
value.1.map {
.init(item: view,
attribute: value.0,
relatedBy: relation,
toItem: nil,
attribute: .notAnAttribute,
multiplier: multiplier,
constant: $0)
}
}
)
}

Install Pod file

Install pod file getting below error

[!] Invalid Podfile file: undefined local variable or method `swift3_overrides' for #Pod::Podfile:0x007fe8020d55b0.

Carthage support

Is it possible for you to add Carthage support for this library? That would be very nice 👍

Not able to show thumbnails of youtube links.

Not able to show thumbnails of youtube links. We had a discussion about the same issue for showing for youtube links that are starting with "m.youtube.com". Now what is happening is if we copy a link from youtube player the link what we are getting is entirely different from all the previous links what we handling.
Adding the code that I'm using to show the URL embedded view below

if sosFeedPostDesc.extractURLs() is URL{
                if  let extractedUrls = sosFeedPostDesc.extractURLs() {
                    let url: URL
                    if (extractedUrls as AnyObject).host?.contains("m.youtube.com") == true {
                        var components = URLComponents(string: (extractedUrls as AnyObject).absoluteString as! String)
                        components?.host = "www.youtube.com"
                        if let _url = components?.url {
                            url = _url
                        } else {
                            url = extractedUrls as! URL
                        }
                    } else {
                        url = extractedUrls as! URL
                    }
                    
                    cell.urlPreviewViewHeightConstraint.constant = 60
                    print("Exrtracted URL: \(url.absoluteString) Index:\(indexPath.row)")
                    
                    let embeddedView = URLEmbeddedView()
                    //                    embeddedView.loadURL(url.absoluteString)
                    embeddedView.load(urlString: url.absoluteString)
                    embeddedView.borderColor = .clear
                    embeddedView.cornerRaidus = 0
                    embeddedView.frame = CGRect(x: 0, y:0, width: cell.frame.width - 20, height: 60)
                    embeddedView.didTapHandler = { [weak self] _, url in
                        guard let url = url else { return }
                        self?.present(SFSafariViewController(url: url), animated: true, completion: nil)
                    }
                    for view in cell.urlEmbededViewOutlet.subviews {
                        if let ev = view as? URLEmbeddedView {
                            ev.cancelLoading()
                            ev.removeFromSuperview()
                        }
                    }
                    
                    cell.urlEmbededViewOutlet.addSubview(embeddedView)
                    
                }
            }
            else{
                for view in cell.urlEmbededViewOutlet.subviews {
                    if let ev = view as? URLEmbeddedView {
                        ev.cancelLoading()
                        ev.removeFromSuperview()
                    }
                }
                cell.urlPreviewViewHeightConstraint.constant = 0
            }

Added the entire code in the descrition. Please suggest if you found any edits in existing code as well. Waiting for to hear from you. Thanks in advance :)

On Xcode 9.3 error message Value of type 'Any' has no member '1' shows.

I updated my Xcode to Xcode 9.3 and this error came out
AutoLayout.swift file, line 34
addConstraints method

func addConstraints(with view: UIView,
                        size: Size,
                        relatedBy relation: NSLayoutRelation = .equal,
                        multiplier: CGFloat = 1) {
        view.translatesAutoresizingMaskIntoConstraints = false
        addConstraints([
                (.width, size.width),
                (.height, size.height)
            ]
            .flatMap { value in
                value.1.map {     /****** THIS IS THE ERROR, type Any has no member '1'  *********/
                    .init(item: view,
                          attribute: value.0,
                          relatedBy: relation,
                          toItem: nil,
                          attribute: .notAnAttribute,
                          multiplier: multiplier,
                          constant: $0)
                }
            }
        )
    }

Sample Project Build Error related to recent fix

"Method 'fetchOGData(urlString:completion:)' with Objective-C selector 'fetchOGDataWithUrlString:completion:' conflicts with method 'fetchOGDataWithUrlString(_:completion:)' with the same Objective-C selector"

Thumbnail not display for link

Hello, still i m facing same issue. I have update pod with version you have mention(0.13.0).
Other than i m facing issue with stack overflow link , it returns me blank view. I have attch screen short for the same. Yes, i have integrated this in objective c.
img_e2296

No fetchOGData in Objective C

How do I call fetchOGData in Objective C. Can you add a sample code for that. I need to fetch URL, siteName, pageTitle, pageDescription.

unable to use it in Objective C project

Tried using it in objective C, even after adding use_frameworks! in podfile, It seems use_frameworks! doesn't work and also tried to add it manually in share extension of my app, but files in URLEmbeddedView source like OGDataProvider unable to access Kanna and Misterfusion files embedded in this pod source, even after adding Kanna and Misterfusion seperately using git clone.

Adding @objc to each OpenGraphData property

Hi,
To compile Objective C under Swift 4, each property needs to add @objc to allow Objective c to access them. Can you help to add the codes below?

@objc public class OpenGraphData: NSObject {
@objc public let createdAt: Date
@objc public let imageUrl: URL?
@objc public let pageDescription: String?
@objc public let pageTitle: String?
@objc public let pageType: String?
@objc public let siteName: String?
@objc public let sourceUrl: URL?
@objc public let updatedAt: Date
@objc public let url: URL?

Thanks for sharing the codes and appreciate it :)

Thanks,
Calvin

Create custom views

Hi,
Can i create a custom view/ tableViewCell?
That has the same capabilities? (open graph caching)

Thansk

How can I get image URL from OpenGraphData?

Hi,

I am using URLEmbeddedView to get meta data. I am not getting image URL since library has been updated. I am using below code to get meta data.

[[OGDataProvider sharedInstance] fetchOGDataWithUrlString:@"www.testurl.com" completion:^(OpenGraphData * obj_data, NSError * error) {

    NSLog(@"data object = %@",obj_data);
}];

So how can I get imageURL, pageTitle, createdAt, pageType, siteName, sourceUrl, url using OpenGraphData object?

Not getting website image for specific URL

I am using this framework for objective C and it's working fine here. But sometimes I am not getting image of particular website and not getting website title properly. Here I am providing you one website URL as sample in which I am facing both issue for image and title.

https://www.cnbc.com/2018/05/02/effectiveness-of-tesla-autopilot-was-not-assessed-nhtsa.html

In above URL I am not getting image and title with uneven characters like &#039;

https://feedproxy.google.com/~r/entrepreneur/latest/~3/EQ33cmQbh3Q/312846

For this URL I am getting null website title. I am using latest code for URLEmbeddedView.

@marty-suzuki Please do needful help for this issue.

Thank you.

Issue with links that do not contain "http://" or "https://"

I've come across an issue where if I try to load a URL that does not contain http:// or https:// that I get a positive response without an error from loadURL, however nothing appears inside the URLEmbeddedView. I got around this by appending the url I try to load with either http:// or https:// but it might be better if the URLEmbeddedView did this automatically or sent back some kind of error to say that the URL is not valid.

メモリ不足警告時にクラッシュ

初めまして。
大変素晴らしいライブラリだと思い触らせていただきました。
表題の状況におきましてCrashlyticsに以下のログを出力しクラッシュいたしましたので、ご報告させていただきます。

CRASH_INFO_ENTRY_1
abort() called
CRASH_INFO_ENTRY_0
Unrecognized selector -[URLEmbeddedView.OGImageCacheManager didReceiveMemoryWarning:]

iOSシミュレータにてメモリ不足警告のシミュレートを行うことでも再現可能でした。
問題の発生は以下の環境で確認いたしました。

  • iPhone 6 / 9.0.2
  • iOSシミュレータ / 9.2

ご参考になればと思います。
よろしくお願いいたします。

OG data is not fully parsed

Tried with version 0.15.3 (we need ios8)
Here are the results of library for url https://www.imdb.com/title/tt5095030/:

createdAt = Wed Jul 18 13:25:53 2018
imageUrl = (null)
pageDescription = Directed by Peyton Reed.  With Paul Rudd, Evangeline Lilly, Michael Peña, Walton Goggins. As Scott Lang balances being both a Super Hero and a father, Hope van Dyne and Dr. Hank Pym present an urgent new mission that finds the Ant-Man fighting alongside The Wasp to uncover secrets from their past.
pageTitle = (null)
pageType = (null)
siteName = (null)
sourceUrl = https://www.imdb.com/title/tt5095030/
updatedAt = Wed Jul 18 13:25:57 2018
url = http://www.imdb.com/title/tt5095030/

While there are not null tags (can be seen in source html, or by tools like https://opengraphcheck.com/result.php?url=https%3A%2F%2Fwww.imdb.com%2Ftitle%2Ftt5095030%2F#.W07dRdgzZTY)

og:url | http://www.imdb.com/title/tt5095030/
og:image | https://m.media-amazon.com/images/M/MV5BYjcyYTk0N2YtMzc4ZC00Y2E0LWFkNDgtNjE1MzZmMGE1YjY1XkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_UY1200_CR90,0,630,1200_AL_.jpg
og:type | video.movie
og:title | Ant-Man and the Wasp (2018)
og:site_name | IMDb
og:description | Directed by Peyton Reed. With Paul Rudd, Evangeline Lilly, Michael Peña, Walton Goggins. As Scott Lang balances being both a Super Hero and a father, Hope van Dyne and Dr. Hank Pym present an urgent new mission that finds the Ant-Man fighting alongside The Wasp to uncover secrets from their past.

Constraints error when setting height to 0

My table view cell is pretty complex, with collapsible elements. URLEmbeddedView can have height 0, if there is no url for that index. But i get constraints error because of internal constraints in URLEmbeddedView:

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x608000492570 V:[UILabel:0x7fd7c7f91d90]-(2)-[UILabel:0x7fd7c7f92010] (active)>

(lldb) po ((UILabel*)0x7fd7c7f92010).superview
<URLEmbeddedView.URLEmbeddedView: 0x7fd7c7f91340; frame = (0 0; 355 0); clipsToBounds = YES; autoresize = RM+BM; layer = <CALayer: 0x608000a21020>>

(lldb) po ((UILabel*)0x7fd7c7f91d90).superview
<URLEmbeddedView.URLEmbeddedView: 0x7fd7c7f91340; frame = (0 0; 355 0); clipsToBounds = YES; autoresize = RM+BM; layer = <CALayer: 0x608000a21020>>

Can you adjust priorities of constraints to accomodate 0 height? Or maybe Relation?

File not found for obj-c

Hi, As mentioned in the obj-c example, there is no file URLEmbeddedView/URLEmbeddedView-Swift.h. Please have a look in to it. I am trying to port that to C#.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.