Firebase Dynamic Links whitelisted - firebase

Hi I have an ios app where I use dynamic links to share content with users, for several months dynamic links worked very well and out of nowhere they stopped working. Does anybody know what is it due to?
During this week I changed the firestore rules, could that affect it?
The console gives me this error:
Error Domain=com.firebase.durabledeeplink Code=0 "We could not match param 'https://www.example.com/post?postId=hy48ndmFLMdxydT7mGPq' with whitelisted URL patterns in this Google project. [https://support.google.com/firebase/answer/9021429] [https://support.google.com/firebase/answer/9021429]" UserInfo={remoteStatus=INVALID_ARGUMENT, NSLocalizedFailureReason=We could not match param 'https://www.example.com/post?postId=hy48ndmFLMdxydT7mGPq' with whitelisted URL patterns in this Google project. [https://support.google.com/firebase/answer/9021429] [https://support.google.com/firebase/answer/9021429], remoteErrorCode=400}
static let scheme = "https"
static let pathPost = "/post"
static let postId = "postId"
static let host = "www.example.com"
static let pageLink = "https://*****.page.link"
static let appId = "*****"
static func getShareLinkPost(post: Post, completion: #escaping FirestoreCompletionLink) {
DispatchQueue.global(qos: .background).async {
var components = URLComponents()
components.scheme = scheme
components.host = host
components.path = pathPost
let userIDQueryItem = URLQueryItem(name: postId, value: post.id)
components.queryItems = [userIDQueryItem]
guard let linkParameter = components.url else {return}
guard let shareLink = DynamicLinkComponents.init(link: linkParameter, domainURIPrefix: pageLink) else {return}
if let myBundleID = Bundle.main.bundleIdentifier {shareLink.iOSParameters = DynamicLinkIOSParameters(bundleID: myBundleID)}
shareLink.iOSParameters?.appStoreID = appId
shareLink.socialMetaTagParameters = DynamicLinkSocialMetaTagParameters()
shareLink.socialMetaTagParameters?.title = "#\(post.user?.username ?? "")"
shareLink.socialMetaTagParameters?.imageURL = URL(string: APPICON)
print(shareLink.link)
shareLink.shorten { (url, warnings, error) in
print(error)
guard let url = url else {return}
completion(url)
}
}
}

Related

How to store videos in Firebase using Swift

I currently have a function that allows me to upload an image to Firebase Storage. But how in the world can I achieve the same, with a video instead of an image?
I suspect I have to change UIImage and .jpg to something else. But what is the type of a video?
#State var pickedImages: [UIImage] = []
#State var retrievedImages = [UIImage]()
This is my function:
func uploadImage() {
// Create storage reference
let storageRef = Storage.storage().reference()
// Turn our image into data
let selectedImage = pickedImages[0]
let imageData = selectedImage.jpegData(compressionQuality: 0.8)
guard imageData != nil else {
let er = "THIS: Error while converting to data"
return print(er)
}
// Specifie filepath and name
let path = "images/\(UUID().uuidString).jpg"
let fileRef = storageRef.child(path)
// Upload that data
let uploadTask = fileRef.putData(imageData!, metadata: nil) {metaData, error in
print("THIS: from uploadTAsk")
// Check for errors
if error == nil && metaData != nil {
// Save reference in firestore DB
let db = Firestore.firestore()
db.collection("images").document("user1").setData(["url": path]) { error in
print("THIS: inside closure")
// If there was no errors, display the image
if error == nil {
DispatchQueue.main.async {
self.retrievedImages.append(selectedImage)
}
}
}
}
}
}

fetch and retrieve data from firebase in swift

what I am trying to do is fetching data from firebase, but the data is nil because the user did not send his data to firebase yet, so when he enter the view controller that should show his data, the compiler make error. How can I solve this error? I tride to add alert, but it's still not working.
func getData(){
ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
ref.child("users")
.queryOrdered(byChild: "uid")
.queryEqual(toValue:userID)
.observe(.value) { (snapshot, error) in
if error == nil{// alert} elses{
if let data = snapshot.value as? NSDictionary {
if snapshot.exists() {
for a in ((snapshot.value as AnyObject).allKeys)!{
let users = data.value(forKey:a as! String) as! NSDictionary
let address = users.value(forKey:"Address") as! NSDictionary
self.lblAddressNickname.text = address.value(forKey:"addressNickname") as? String
}
}
}
}
}
}
So as of now i understand the question that you have problem in fetching data from firebase when no data is in the firebase and then alert will come and it will redirect to a new controller?
So based on my understanding i will give answer if any problem of understanding things then reply me?
first you have to check that particular user have any data in firebase database so if there is no data then alert function will call
if let data == data
{
fetch_logic is here
}
else
{
let alert = UIAlertController(title:"Add Data",message:"",preferredStyle: .alert)
let action = UIAlertAction(title: "Add Button", style: .default) { (UIAlertAction) in
}
alert.addAction(action)
present(alert,animation:true,completion:true)
}

Swift 3: Image downloaded from Firebase and saved to local storage not showing in app

I am trying out a firebase storage function and I am unable to show the downloaded image in imageview. Download is successful but nothing shows. If I use a Image from assets it does show. Why is this not working?
DownloadViewController:
import UIKit
import FirebaseStorage
import Firebase
#objc(DownloadViewController)
class DownloadViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var statusTextView: UITextView!
var storageRef: FIRStorageReference!
override func viewDidLoad() {
super.viewDidLoad()
storageRef = FIRStorage.storage().reference()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let filePath = "file:\(documentsDirectory)/myimage.jpg"
let storagePath = UserDefaults.standard.object(forKey: "storagePath") as! String
// [START downloadimage]
storageRef.child(storagePath).write(toFile: URL.init(string: filePath)!,
completion: { (url, error) in
if let error = error {
print("Error downloading:\(error)")
self.statusTextView.text = "Download Failed"
return
}
self.statusTextView.text = "Download Succeeded!"
print("filepath: "+filePath)
let image = UIImage.init(contentsOfFile: filePath)
self.imageView.image = image
self.imageView.layoutIfNeeded()
self.imageView.clipsToBounds = true
})
// [END downloadimage]
}
}
Try adding .resume at the end of your function block like so:
}).resume
I assume the issue here is that your file doesn't exist:
let filePath = "file:\(documentsDirectory)/myimage.jpg"
Likely doesn't resolve to the correct user documents directory, and you should use something like (pardon the Obj-C, already answered this question with it):
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:#"hello"] URLByAppendingPathExtension:#"txt"];
This will also prevent issues of "works on the simulator but doesn't work on a device" and vice-versa.

How to load image from URL on watchos 2?

Is there any framework can be used to load an image from URL in watchos 2 ? I tried SDWebImage but it doesn't support watchos2?
Its no framwork, but I've written this extension:
extension WKInterfaceImage {
public func imageFromUrl(_ urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSURLRequest(url: url as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let imageData = data as Data? {
DispatchQueue.main.async {
self.setImageData(imageData)
}
}
});
task.resume()
}
}
}
Just add a WKInterfaceImage to your watchOS storyboard, attach it and then call
imageView.imageFromUrl("https://something")
Let me know if it works!

Trouble uploading videos from iOS using WordPress REST api

I am very new at this, so sorry if I have missed something.
I am trying to upload a video from iOS to WordPress using the WP REST API and Alamofire.
Some videos will upload just fine while other videos get a rest_upload_no_content_disposition status = 400 error.
Here is my code to uploading a video
class func pageVideo(accessToken:String, filePath:NSURL, completion: AnyObject? -> Void) {
let endpoint = "http://XXXXXXXXX.com/wp-json/wp/v2/media/?access_token=\(accessToken)"
let parameters = [
"Content-Type": "multipart/form-data",
"Content-Disposition": "attachment; filename=appVideo.mov",
"media_type": "file"
]
var fileData : NSData?
if let fileContents = NSFileManager.defaultManager().contentsAtPath(filePath.path!) {
fileData = fileContents
}
let mgr = Alamofire.Manager.sharedInstance
mgr.upload(.POST, endpoint, multipartFormData: { multipartFormData in
if let _fileData = fileData {
multipartFormData.appendBodyPart(data: _fileData, name: "file", fileName: "file.mov", mimeType: "file/mov")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.response {(request, response, data, error ) in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
if let dict = json as? NSDictionary{
if let url = dict.valueForKeyPath("source_url") as? String{
completion(url)
}
}
} catch let error as NSError{
// completion(error.localizedDescription)
print(error.localizedDescription)
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
}
It seems like shorter videos work while anything over 30 seconds fails.
Even shorter videos that do upload take a very long time.
Any help would be greatly appreciated.
Nothing was wrong with my code I just needed to compress the videos. the longer videos were hitting the WordPress upload limit. Also it's always a good idea to compress videos or images that your uploading somewhere.

Resources