How to add OFL link in Firebase dynamic linking iOS Swift? - swift

How to add OFL link in Firebase dynamic linking iOS Swift?
open a Firebase dynamic link in desktop, to redirect a particular website Swift.

guard let link = URL(string: "url") else { return }
let dynamicLinksDomainURIPrefix = "prefixlik"
guard let shareLink = DynamicLinkComponents(link: link, domainURIPrefix: dynamicLinksDomainURIPrefix) else {
print("Could not create firebace dynamiclink on console")
return
}
if let myBundleId = Bundle.main.bundleIdentifier {
shareLink.iOSParameters = DynamicLinkIOSParameters(bundleID: myBundleId)
}
shareLink.iOSParameters?.appStoreID = "XXXXXXXXX"
shareLink.androidParameters = DynamicLinkAndroidParameters(packageName: "XXXXXXXX")
guard let longDynamicLink = shareLink.url else { return }
print("The long URL is: \(longDynamicLink)")
DynamicLinkComponents.shortenURL(URL(string: "\(longDynamicLink)&ofl=https://google.com/")!, options: nil) { (url, warnings, error) in
if let error = error {
print("Oh no! Got an error ",error.localizedDescription)
return
}
if let warnings = warnings {
for warning in warnings {
print("FDL warning: \(warning)")
}
}
guard let shortUrl = url else {return}
print(shortUrl) }

Related

Facing issues with ContentBlockerRequestHandler of Safari extension

I am currently working on a safari app extension that blocks content. I want the user to configure the rule (turning a rule on and off). Since I can’t overwrite the bundled JSON files and we can’t write to the documents folder, as it’s not accessible to the extension I decided to use App Groups. My approach looks like this:
Within the ContentBlockerRequestHandler I want to save the blockerList.json into the app group (Only when launched for the first time)
When this is done I want that the handler reads from the app group by taking the url of my json which is within the app group instead of taking the default json in the extension
Since I can not debug the handler I don't know if I am on the right path. The following shows my code:
class ContentBlockerRequestHandler: NSObject, NSExtensionRequestHandling {
func beginRequest(with context: NSExtensionContext) {
guard let rulesUrl = loadRules() else {
let clonedRules = cloneBlockerList()
save(rules: clonedRules)
return
}
guard let attachment = NSItemProvider(contentsOf: rulesUrl) else { return }
let item = NSExtensionItem()
item.attachments = [attachment]
context.completeRequest(returningItems: [item], completionHandler: nil)
}
private func cloneBlockerList() -> [Rule] {
var rules: [Rule] = []
if let url = Bundle.main.url(forResource: "blockerList", withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(ResponseData.self, from: data)
rules = jsonData.rules
} catch {
print("error:(error)")
}
}
return rules
}
private func save(rules: [Rule]) {
let documentsDirectory = FileManager().containerURL(forSecurityApplicationGroupIdentifier: "my group identifier")
let archiveURL = documentsDirectory?.appendingPathComponent("rules.json")
let encoder = JSONEncoder()
if let dataToSave = try? encoder.encode(rules) {
do {
try dataToSave.write(to: archiveURL!)
} catch {
// TODO: ("Error: Can't save Counters")
return;
}
}
}
private func loadRules() -> URL? {
let documentFolder = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "my group identifier")
guard let jsonURL = documentFolder?.appendingPathComponent("rules.json") else {
return nil
}
return jsonURL
}
}
Thankful for any help

How to make call form iOS swift with IVR call (i.e. #123#) from swift app on button click

I am trying to implement call on #123# in swift when user click on button. I am writing below code to make a call but it's not working.
let iVRPhoneNumber = "#123#"
guard let url = URL(string: "tel://\(iVRPhoneNumber)") else { return }
//It's alwasy returning from here. If I removed # from iVRPhoneNumber string then it's working.
if let phoneCallURL = URL(string: "tel://\(iVRPhoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
}
}
Adding percentage encoding to the phone number string should work,
let iVRPhoneNumber = "#123#"
guard let phoneNumber = iVRPhoneNumber.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return }
guard let phoneCallURL = URL(string: "tel://\(phoneNumber)") else { return }
print(phoneCallURL)
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
}

Getting an error when implementing drop support for my Mac application

I'm trying to get the URL of a web page when it's dragged into my application view. I'm using the code below as the DropDelegate.
func performDrop(info: DropInfo) -> Bool {
guard let itemProvider = info.itemProviders(for: ["public.url"]).first else {
return false
}
guard itemProvider.canLoadObject(ofClass: URL.self) else {
return false
}
_ = itemProvider.loadObject(ofClass: URL.self) {url, _ in
if let url = url {
DispatchQueue.main.async {
do {
try self.store.urlToOpen = url.absoluteString
} catch {
}
}
}
}
return true
}
The error I'm getting is:
Could not instantiate class NSURL. Error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive
I'm not sure what's going on and how to fix this. Any ideas?
Here is working solution. Tested with Xcode 12 / macOS 10.15.5
_ = itemProvider.loadDataRepresentation(forTypeIdentifier: "public.url") {url, _ in
if let data = data,
let path = String(bytes: data, encoding: .utf8),
let url = URL(string: path) {
DispatchQueue.main.async {
do {
try self.store.urlToOpen = url.absoluteString
} catch {
}
}
}
}

Swift storing PKPass with Firebase

I'm trying to save the PKPass with Firebase so that I'm not generating the pass every time the user wants to add the pass to the waller or send the pass. I'm storing the pass.passURL in my firebase database and then fetching it again when the user wants to do something with the pass. Right now all that is happening is the Wallet is opening but the pass isn't showing up. Is this the best way to store the PKPass
Save Function:
func saveTicketIdToDB(pass: PKPass) {
guard let uid = Auth.auth().currentUser?.uid else { return }
guard let postId = post?.postId else { return }
guard let paymentId = paymentId else { return }
guard let passUrl = pass.passURL as? URL else { return }
let passUrlString: String = passUrl.absoluteString
let values = ["passUrl": passUrlString]
let db = Firestore.firestore()
db.collection("payments").document(postId).collection("purchases").document(paymentId).updateData(values) { (error) in
if let error = error {
print("There was an error", error.localizedDescription)
return
}
print("Successfully saved pkpass into database.")
}
}
Opening in wallet:
guard let passUrlData = URL(string: passUrl) else { return }
if #available(iOS 10.0, *) {
UIApplication.shared.open(passUrlData, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(passUrlData)
}
You need to store the entire PKPass bundle as a data blob. Then re-create it using PKPass.init(data: ...) and use the PassKit APIs to see if it's in the Wallet already.

How to add or delete rule of safari content block list at run time

I am using in my project safari content blocker extension. when i set the rule in blockerList.json file statically and run the project every thing is working fine. Now i want to set my rule dynamically using the technic as it describes in below.
Guys please help me out to set the rule dynamically at run time.
I try this but i am getting an error when
load from viewcontroller class
fileprivate func saveRuleFile() {
let ruleList = [["trigger":["url-filter": ".*"],"action":["type": "block"]]]
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
if let encoded = try? encoder.encode(ruleList) {
let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.****.***")
print("sharedContainerURL = \(String(describing: sharedContainerURL))")
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}
if let destinationURL = sharedContainerURL?.appendingPathComponent("Rules.json") {
do {
try encoded.write(to: destinationURL)
} catch {
print (error)
}
}
}
}
And write this in ContentBlockerRequestHandler class
func beginRequest(with context: NSExtensionContext) {
let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.****.***")
let sourceURL = sharedContainerURL?.appendingPathComponent("Rules.json")
let ruleAttachment = NSItemProvider(contentsOf: sourceURL)
let item = NSExtensionItem()
item.attachments = ([ruleAttachment] as! [NSItemProvider])
context.completeRequest(returningItems: [item], completionHandler: nil)
}
i try to load using
SFContentBlockerManager.reloadContentBlocker(withIdentifier: "com.app.*****", completionHandler: {(error) in
if error != nil{
print("error: \(error.debugDescription)")
}
})
when try to execute 3rd number block at run time i'm getting an error. But i go to the file path and checked the json is absolutely fine, its a valid json there.
Error Domain=WKErrorDomain Code=2 "(null)" UserInfo={NSHelpAnchor=Rule list compilation failed: Failed to parse the JSON String.}
Try to use JSONSerialization. It work great for me :)
fileprivate func saveRuleFile() {
let ruleList = [["trigger":["url-filter": ".*"],"action":["type": "block"]]]
let jsonAsData = try! JSONSerialization.data(withJSONObject: ruleList)
let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.****.***")
print("sharedContainerURL = \(String(describing: sharedContainerURL))")
if let destinationURL = sharedContainerURL?.appendingPathComponent("Rules.json") {
do {
try jsonAsData.write(to: destinationURL)
} catch {
print (error)
}
}
}