ios - Added site is not blocked with content blocker -


hi writing simple content blocker app. in app want allow user add website wants block , block reasons content blocker doesn't block newly added website reasons. used sfcontentblockermanager.reloadcontentblocker(withidentifier: blockeridentifier) prints success reasons doesn't work.

import uikit import cartography import swiftyjson import safariservices  protocol myprotocol{   func deletesite(num:int) }   class viewcontroller: uiviewcontroller, uitableviewdelegate, uitableviewdatasource, myprotocol { var tableview: uitableview = uitableview() var arr = [string]() func deletesite(num: int) {      if let path = bundle.main.path(forresource: "blockerlist", oftype: "json"){         guard let data = nsdata(contentsof: url(fileurlwithpath: path)) else{             return         }   //      json(data: data data)[num] = nil         var jsonobj = json(data: data data)      //   jsonobj.arrayobject?.remove(at: num)         print(jsonobj)         if jsonobj != json.null {            // jsonobj.arrayobject[num] =             jsonobj[num] = nil            //  print("hello work here \(jsonobj.arrayvalue.remove(at: num))")             tableview.reloaddata()            // jsonobj.arrayobject?.remove(at: num)          } else {             print("could not json file, make sure file contains valid json.")         }     }  }   override func viewdidload() {     super.viewdidload()     let blockeridentifier = "saltaim.selfcontrol2.blocker"     sfcontentblockermanager.reloadcontentblocker(withidentifier: blockeridentifier) {error in         if error == nil {             print("success")         } else {             print("----------------------------------------------")             print(error)             print("----------------------------------------------")          }     }      super.view.backgroundcolor = uicolor.red;      //let blockeridentifier = "com.appsfoundation.contentblocker.blocker"     //sfcontentblockermanager.     // print("--------------------")     //print(filemanager.default.c)     //bundle(for: contentblockerrequesthandler)     //print(bundle.main.path(forresource: "blocker/blockerlist", oftype: "json"))     //print(bundle.main.path(forresource: "blockerlist", oftype: "json"))      //print("--------------------")     //bundle.main.url     //bundle.main.pa     //filemanager.default.containerurl(forsecurityapplicationgroupidentifier: <#t##string#>)     // print(bundle.main.url(forresource: "blocker/blockerlist", withextension: "json"))     // bundle.init(for: contentblockerrequesthandler)     // print(bundle.main.paths(forresourcesoftype: "blockerlist.json", indirectory: "blocker"))     tableview.register(mytableviewcell.self, forcellreuseidentifier: "cell")      if let path = bundle.main.path(forresource: "blockerlist", oftype: "json"){         guard let data = nsdata(contentsof: url(fileurlwithpath: path)) else{             return         }         let jsonobj = json(data: data data)         print(jsonobj)         if jsonobj != json.null {             // print("hello work here \(jsonobj["trigger"])")             guard let arr1 = jsonobj.array else{                 return;             }             var count = arr1.count;             index in 0...count-1{                 //print("-------")                 // print(jsonobj[index]["trigger"]["url-filter"].stringvalue)                 arr.append(jsonobj[index]["trigger"]["url-filter"].stringvalue);               }             //for          } else {             print("could not json file, make sure file contains valid json.")         }         //       }     // arr.append("hello")     // arr.append("my name ")     let button = uibutton();     button.settitle("+", for: .normal)     button.addtarget(self, action: #selector(buttonpressed), for: .touchupinside)     // button.titlelabel?.text = "+"      self.view.addsubview(tableview)     self.view.addsubview(button)     tableview.delegate = self     tableview.datasource = self     constrain(tableview, view, button){         tableview, view, button in         tableview.width == view.width         tableview.height == view.height - 50         tableview.top == view.top         tableview.right == view.right         button.height == 50         button.width == view.width         button.top == view.bottom - 50         button.right == view.right      }     //arr = array()     // additional setup after loading view, typically nib.     // self.view.backgroundcolor = uicolor.redcolor(); } func buttonpressed(){     // print("i pressed")     //var alert = uialertview();     //alert.title = "enter website";     // alert.alertviewstyle = uialertviewstyle.plaintextinput     // alert.addb     //alert.addbutton(withtitle: "done")     //alert.addbutton(withtitle: "cancel")     var s:string?     var alert = uialertcontroller(title: "alert", message: "enter website block", preferredstyle: uialertcontrollerstyle.alert)      alert.addtextfield { (text) in         text.placeholder = "http://";         s=text.text     }     let action = uialertaction(title: "done", style: uialertactionstyle.default) { (action: uialertaction) in         guard let s = alert.textfields?[0].text else{             return         }          //var c = ["action":["type": "block"], "trigger":["url-filter":s]];         //print(c)         let path = bundle.main.path(forresource: "blockerlist", oftype: "json")!         var readstring = "" // used store file contents         {             // read file contents             readstring = try string.init(contentsof: url(fileurlwithpath: path))             //readstring = fileurl.absolutestring             // readstring = try string(contentsofurl: fileurl)         } catch let error nserror {             print("failed reading url: \(url(fileurlwithpath: path)), error: " + error.localizeddescription)         }        // var size = (readstring.characters.count - 1)         //print("the end index \(readstring.endindex)")         print("------------------------")         readstring = readstring.replacingoccurrences(of: "]", with: "")       //  print(readstring.endindex)        // readstring = string(readstring.characters.droplast())         print(readstring)         print("--------------------------")        // readstring.remove(at: readstring.endindex)        // readstring = readstring.substring(to: readstring.index(before: readstring.endindex))         readstring += ",{\"action\":{\"type\":\"block\"},\"trigger\":{\"url-filter\":\"" + s+"\"}}]"         print("file text: \(readstring)")   //      let filename = "blockerlist"       //  let documentdirurl = try! filemanager.default.url(for: ., in: .userdomainmask, appropriatefor: nil, create: true)      //   let fileurl = documentdirurl.appendingpathcomponent(filename).appendingpathextension("json")         print("filepath: \(path)")         let filehandler = try! filehandle(forwritingto: url(fileurlwithpath: path))         //filehandler.         //filehandler.seektoendoffile()         filehandler.write(readstring.data(using: string.encoding.utf8, allowlossyconversion: false)!)         // filehandler.write("hello".data(using: string.encoding.utf8, allowlossyconversion: false)!)        // filehandler.write(c.description.data(using: string.encoding.utf8, allowlossyconversion: false)!)         filehandler.closefile()         var readstring1 = "" // used store file contents         {             // read file contents             readstring1 = try string.init(contentsof: url(fileurlwithpath: path))             //readstring = fileurl.absolutestring             // readstring = try string(contentsofurl: fileurl)         } catch let error nserror {             print("failed reading url: \(url(fileurlwithpath: path)), error: " + error.localizeddescription)         }         print("file text: \(readstring1)")         let blockeridentifier = "saltaim.selfcontrol2.blocker"         sfcontentblockermanager.reloadcontentblocker(withidentifier: blockeridentifier) {error in             if error == nil {                 print("success")             } else {                 print("----------------------------------------------")                 print(error)                 print("----------------------------------------------")              }         }        }     let action2 = uialertaction(title: "cancel", style: uialertactionstyle.cancel) { (uialertaction) in         self.dismiss(animated: true, completion: nil)     }     alert.addaction(action)     alert.addaction(action2)     self.present(alert, animated: true, completion: nil)     //self.viewc     //presentedviewcontroller(alert)     //alert.adda     // alert.show() }  override func didreceivememorywarning() {     super.didreceivememorywarning()      // dispose of resources can recreated. } func numberofsections(in tableview: uitableview) -> int {     return 1 } func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int {     return arr.count  }  func tableview(_ tableview: uitableview, heightforrowat indexpath: indexpath) -> cgfloat {     return 50 }  func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell {     // code here     // let cell = uitableviewcell(style: uitableviewcellstyle.default, reuseidentifier: "cell")     var site = arr[(indexpath nsindexpath).item]     let cell = mytableviewcell(num: (indexpath nsindexpath).item,site: site, style: uitableviewcellstyle.default, reuseidentifier: "cell")     cell.delegate = self;     // let cell = mytableviewcell(style: uitableviewcellstyle.default, reuseidentifier: "cell")     // cell.site = arr[(indexpath nsindexpath).item]      // let cell1 = mytableviewcell();      // let cell = mytablev     //cell.t     //let cell1 = tableview.dequeuereusablecell(withidentifier: "cell")     //cell.textlabel?.text = "hello"     //cell.textlabel?.text = arr[(indexpath nsindexpath).item]     return cell; }    } 

i ran similar issue when wrote own content blocker. when create content-blocker extension create json file extension reads from. now, important part extension reads file located in extension's bundle directory.

from can see writing json file in main app bundle , reloading content blocker. content blocker looks @ file in it's own directory (again, seperate main bundle directory) , loads json file.

to resolve this, need write file changes json file located in extensions bundle directory.

here's example:

let groupurl: nsurl = filemanager.containerurlforsecurityapplicationgroupidentifier("group.com.mygroup")!  if let path = nsurl(string: "blockerlist.json", relativetourl: groupurl) {     // write json data path here     sfcontentblockermanager.reloadcontentblockerwithidentifier("com.my.extension.identifier", completionhandler: nil) } 

another important thing note you'll have request special permissons read , write extension's bundle.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -