diff --git a/.gitignore b/.gitignore
index e9dc58d..994838d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,5 @@
.pub/
build/
+
+example/.flutter-plugins-dependencies
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index b86f08e..6f60124 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -3,12 +3,8 @@
-
-
-
-
@@ -34,19 +30,13 @@
-
-
-
+
+
+
+
+
+
@@ -56,12 +46,6 @@
-
-
-
-
-
-
@@ -76,6 +60,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
@@ -102,4 +98,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e5bd10..8540b99 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,9 @@
+## 0.1.5
+
+* Refactor from events to method call
+* Remove loading state (handle that in app)
+* Better error handling
+
## 0.1.4
* Fix iOS bug
diff --git a/android/src/main/kotlin/com/n1k3c/link_preview/LinkPreviewPlugin.kt b/android/src/main/kotlin/com/n1k3c/link_preview/LinkPreviewPlugin.kt
index 10c8531..9effb14 100644
--- a/android/src/main/kotlin/com/n1k3c/link_preview/LinkPreviewPlugin.kt
+++ b/android/src/main/kotlin/com/n1k3c/link_preview/LinkPreviewPlugin.kt
@@ -1,21 +1,20 @@
package com.n1k3c.link_preview
+import com.leocardz.link.preview.library.LinkPreviewCallback
+import com.leocardz.link.preview.library.SourceContent
+import com.leocardz.link.preview.library.TextCrawler
+import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
-import com.leocardz.link.preview.library.SourceContent
-import com.leocardz.link.preview.library.LinkPreviewCallback
-import com.leocardz.link.preview.library.TextCrawler
-import io.flutter.plugin.common.EventChannel
-import java.util.*
private const val STATE = "state"
-private const val STATE_LOADING = "loading"
private const val STATE_SUCCESS = "success"
-private const val STATE_ERROR = "error"
+private const val STATE_PARSING_ERROR = "parsing_error"
+private const val STATE_WRONG_URL = "wrong_url_error"
private const val FIELD_TITLE = "title"
private const val FIELD_DESC = "description"
@@ -28,26 +27,33 @@ private const val FIELD_IMAGE = "image"
private const val ERROR_TYPE = "Link preview error"
-class LinkPreviewPlugin : EventChannel.StreamHandler {
+class LinkPreviewPlugin : MethodCallHandler {
+
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
- val eventChannel = EventChannel(registrar.messenger(), "link_preview_events")
- eventChannel.setStreamHandler(LinkPreviewPlugin())
+ val channel = MethodChannel(registrar.messenger(), "link_preview_channel")
+ channel.setMethodCallHandler(LinkPreviewPlugin())
}
}
- override fun onListen(arguments: Any, event: EventChannel.EventSink) {
+ override fun onMethodCall(call: MethodCall, result: Result) {
+ if (call.method.equals("previewLink")) {
+ val url: String? = call.argument("url")
+ previewLink(url, result)
+ } else {
+ result.notImplemented()
+ }
+ }
+
+ private fun previewLink(url: String?, result: Result) {
val data = mutableMapOf()
val textCrawler = TextCrawler()
val linkPreviewCallback = object : LinkPreviewCallback {
- override fun onPre() {
- data[STATE] = STATE_LOADING
- event.success(data)
- }
+ override fun onPre() {}
override fun onPos(sourceContent: SourceContent, b: Boolean) {
if (sourceContent.isSuccess) {
@@ -61,23 +67,19 @@ class LinkPreviewPlugin : EventChannel.StreamHandler {
data[FIELD_ROW] = sourceContent.raw
data[FIELD_HTML_CODE] = sourceContent.htmlCode
- event.success(data)
- event.endOfStream()
+ result.success(data)
} else {
- event.error(ERROR_TYPE, "Parsing URL error. Check your URL for typos and/or your connection", "")
- event.endOfStream()
+ data[STATE] = STATE_PARSING_ERROR
+ result.success(data)
}
}
}
- val url: String? = arguments.toString()
-
- if (url.isNullOrBlank()) event.error(ERROR_TYPE, "URL is blank", "")
+ if (url.isNullOrBlank()) {
+ data[STATE] = STATE_WRONG_URL
+ result.success(data)
+ }
textCrawler.makePreview(linkPreviewCallback, url)
}
-
- override fun onCancel(p0: Any?) {
-
- }
}
diff --git a/example/lib/main.dart b/example/lib/main.dart
index f839557..2741925 100644
--- a/example/lib/main.dart
+++ b/example/lib/main.dart
@@ -23,17 +23,25 @@ class _MyAppState extends State {
Future getLinks() async {
try {
- await LinkPreview.getPreview('https://google.com',
- onData: (PreviewResponse data) => _previewData(data),
- onError: (error) => _handleError(error));
+ PreviewResponse previewResponse = await LinkPreview.getPreview('https://google.com');
+ _previewData(previewResponse);
+
+ PreviewResponse previewResponse2 = await LinkPreview.getPreview('https://facebook.com');
+ _previewData(previewResponse2);
+
+ PreviewResponse previewResponse3 = await LinkPreview.getPreview('https://amazon.com');
+ _previewData(previewResponse3);
} on PlatformException {
print('Error occured!!');
}
}
_previewData(PreviewResponse previewResponse) {
- if (previewResponse.status == PreviewStatus.complete) {
- _linkTitle = previewResponse.title;
+ if (previewResponse.status == PreviewStatus.success) {
+ setState(() {
+ _linkTitle = previewResponse.title;
+ });
+
print('===============================================');
print('Received status: ${previewResponse.status}');
print('Received title: ${previewResponse.title}');
@@ -45,19 +53,24 @@ class _MyAppState extends State {
print('Received html code: ${previewResponse.htmlCode}');
print('Received row: ${previewResponse.row}');
print('===============================================');
+ } else if (previewResponse.status == PreviewStatus.wrongUrlError) {
+ print('===============================================');
+ print('Received status: ${previewResponse.status}');
+ print('Wrong URL');
+ print('===============================================');
+ } else if (previewResponse.status == PreviewStatus.parsingError) {
+ print('===============================================');
+ print('Received status: ${previewResponse.status}');
+ print('Parsing URL error');
+ print('===============================================');
} else {
print('===============================================');
print('Received status: ${previewResponse.status}');
+ print('Other error');
print('===============================================');
}
}
- static _handleError(error) {
- print('===============================================');
- print('Received error: ${error.message}');
- print('===============================================');
- }
-
@override
Widget build(BuildContext context) {
return MaterialApp(
diff --git a/ios/Classes/SwiftLinkPreviewPlugin.swift b/ios/Classes/SwiftLinkPreviewPlugin.swift
index 5e15042..56b5ae4 100644
--- a/ios/Classes/SwiftLinkPreviewPlugin.swift
+++ b/ios/Classes/SwiftLinkPreviewPlugin.swift
@@ -3,14 +3,15 @@ import UIKit
import SwiftLinkPreview
enum ChannelName {
- static let linkPreview = "link_preview_events"
+ static let linkPreview = "link_preview_channel"
}
enum State {
static let state = "state"
static let loading = "loading"
static let success = "success"
- static let error = "error"
+ static let parsingError = "parsing_error"
+ static let wrongUrlError = "wrong_url_error"
}
enum Field {
@@ -28,64 +29,47 @@ enum Error {
static let errorType = "Link preview error"
}
-public class SwiftLinkPreviewPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
-
- private var eventSink: FlutterEventSink?
+public class SwiftLinkPreviewPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
- let linkPreviewChannel = FlutterEventChannel(name: ChannelName.linkPreview,
+ let linkPreviewChannel = FlutterMethodChannel(name: ChannelName.linkPreview,
binaryMessenger: registrar.messenger())
- linkPreviewChannel.setStreamHandler(SwiftLinkPreviewPlugin())
+ registrar.addMethodCallDelegate(SwiftLinkPreviewPlugin(), channel: linkPreviewChannel)
}
-
- public func onListen(withArguments arguments: Any?, eventSink: @escaping FlutterEventSink) -> FlutterError? {
- self.eventSink = eventSink
-
- guard let url = arguments as? String else {
- let error = FlutterError(code: Error.errorType, message: "Parsing URL error. Check your URL for typos and/or your connection", details: "")
- eventSink(error)
- return nil
- }
-
- previewLink(url: url)
- return nil
- }
-
- private func previewLink(url: String) {
- guard let eventSink = eventSink else {
- return
- }
-
- eventSink([State.state : State.loading])
-
- let slp = SwiftLinkPreview(session: URLSession.shared,
- workQueue: SwiftLinkPreview.defaultWorkQueue,
- responseQueue: DispatchQueue.main,
- cache: DisabledCache.instance)
-
- slp.preview(url,
- onSuccess: {
- result in print("\(result)")
- let result = [State.state : State.success,
- Field.title : result.title,
- Field.description : result.description,
- Field.url : result.url?.absoluteString,
- Field.finalUrl : result.finalUrl?.absoluteString,
- Field.cannonicalUrl : result.canonicalUrl!,
- Field.image : result.image]
- eventSink(result)
- },
- onError: {
- error in print("\(error)")
- eventSink(FlutterError(code: Error.errorType, message: "Parsing URL error. Check your URL for typos and/or your connection", details: ""))
- })
- }
-
- public func onCancel(withArguments arguments: Any?) -> FlutterError? {
- eventSink = nil
- return nil
- }
+
+ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ if(call.method.elementsEqual("previewLink")){
+ let arguments = call.arguments as? NSDictionary
+ guard let url = arguments!["url"] as? String else {
+ result([State.state : State.wrongUrlError])
+ return
+ }
+
+ let slp = SwiftLinkPreview(session: URLSession.shared,
+ workQueue: SwiftLinkPreview.defaultWorkQueue,
+ responseQueue: DispatchQueue.main,
+ cache: DisabledCache.instance)
+
+ slp.preview(url,
+ onSuccess: {
+ res in print("\(res)")
+ let data = [State.state : State.success,
+ Field.title : res.title,
+ Field.description : res.description,
+ Field.url : res.url?.absoluteString,
+ Field.finalUrl : res.finalUrl?.absoluteString,
+ Field.cannonicalUrl : res.canonicalUrl!,
+ Field.image : res.image]
+ result(data)
+
+ },
+ onError: {
+ error in print("\(error)")
+ result([State.state : State.parsingError])
+ })
+ }
+ }
}
diff --git a/lib/link_preview.dart b/lib/link_preview.dart
index c3bccf1..0216044 100644
--- a/lib/link_preview.dart
+++ b/lib/link_preview.dart
@@ -1,36 +1,28 @@
import 'dart:async';
-import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
class LinkPreview {
- static const EventChannel eventChannel = EventChannel('link_preview_events');
+ static const MethodChannel _methodChannel =
+ MethodChannel('link_preview_channel');
- static Future getPreview(String url,
- {@required Function(PreviewResponse model) onData,
- @required Function onError}) async {
- return eventChannel
- .receiveBroadcastStream(url)
- .listen(
- (dynamic event) => _mapData(event, onData),
- onError: (dynamic error) => onError(error),
- )
- .asFuture();
+ static Future getPreview(String url) async {
+ Map args = {};
+ args.putIfAbsent("url", () => url);
+
+ var result = await _methodChannel.invokeMethod("previewLink", args);
+ PreviewResponse previewResponse = _mapResultToResponse(result);
+ return previewResponse;
}
- static _mapData(dynamic event, Function(PreviewResponse model) onData) {
- var data = Map.from(event);
+ static PreviewResponse _mapResultToResponse(dynamic result) {
+ var data = Map.from(result);
- PreviewStatus status;
+ PreviewResponse previewResponse;
- if (data['state'] == 'loading') {
- status = PreviewStatus.loading;
- PreviewResponse previewModel = PreviewResponse(status);
- onData(previewModel);
- } else {
- status = PreviewStatus.complete;
- PreviewResponse previewModel = PreviewResponse(
- status,
+ if (data['state'] == 'success') {
+ previewResponse = PreviewResponse(
+ PreviewStatus.success,
title: data['title'],
description: data['description'],
image: data['image'],
@@ -39,10 +31,16 @@ class LinkPreview {
cannonicalUrl: data['cannonical_url'],
row: data['row'],
htmlCode: data['html_code'],
-
);
- onData(previewModel);
+ } else if (data['state'] == 'wrong_url_error') {
+ previewResponse = PreviewResponse(PreviewStatus.wrongUrlError);
+ } else if (data['state'] == 'parsing_error') {
+ previewResponse = PreviewResponse(PreviewStatus.parsingError);
+ } else {
+ previewResponse = PreviewResponse(PreviewStatus.otherError);
}
+
+ return previewResponse;
}
}
@@ -68,4 +66,4 @@ class PreviewResponse {
this.htmlCode});
}
-enum PreviewStatus { loading, complete }
+enum PreviewStatus { success, wrongUrlError, parsingError, otherError }
diff --git a/pubspec.yaml b/pubspec.yaml
index 39b8c3f..ccfbddb 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -2,7 +2,7 @@ name: link_preview
description: Plugin for previewing links
author: n1k3c
homepage: https://github.com/n1k3c/flutter-link-preview
-version: 0.1.4
+version: 0.1.5
environment:
sdk: ">=2.1.0 <3.0.0"