PdfKit Annotations Highlight & Save IOS 11 - swift

Is there any helpful walkthrough on how to use the pdfkit annotations(highlight, comments, etc..) and save the results in swift.
I couldn’t find a helpful one.
Thank you

For Highlight you can use following code :
let selections = self.pdfview.currentSelection?.selectionsByLine()
// Simple scenario, assuming your pdf is single-page.
guard let page = selections?.first?.pages.first else { return }
if selections == nil {
}else {
selections?.forEach({ selection in
let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
// highlight.endLineStyle = .square
highlight.color = UIColor(red:0.49, green:0.99, blue:0.00, alpha:1.0).withAlphaComponent(0.5)
page.addAnnotation(highlight)
})
}
For Save :
self.pdfdocument?.write(to: urlPath!)

Related

How to display all pictures from firebase folder with good animation swift

So I have a folders of images in firebase and all the folders have a name, when in viewcontriller I press the button with specific name I need to receive images from the folder with same name. I have done it with just for each loop, here is the cod of my realization:
db.collection(name!).getDocuments { (snapshot, error) in
if error == nil && snapshot != nil {
var paths = [String]()
for doc in snapshot!.documents{
paths.append(doc["url"] as! String)
}
for path in paths{
let storageRef = Storage.storage().reference()
// Specify the path
let fileRef = storageRef.child(path)
// Retrive the data
fileRef.getData(maxSize: 5 * 1024 * 1024) { (data, error) in
if error == nil && data != nil{
// Create a UIImage and put it into our array for display
if let image = UIImage(data: data!){
DispatchQueue.main.async {
self.retriewedImages.append(image)
let button = UIButton(frame: CGRect(x: 10+counterX, y: 200+counterY, width: 100, height: 200))
button.setImage(image, for: .normal)
self.view.addSubview(button)
counterY = counterY + 210
if counterY == 420{
counterY = 0
counterX = counterX + 110
}
}
}
}
}
}
}
}
}
I have done in in override func viewDidLoad()
So the main problem is that firstly when view controller appears i have ugly animation when that pictures one by one appear, I need some decision or hove instantly show all of them when that view controller appears (the best way will be if they appear with view contoller), probably i need to use for each loop to create array of pictures and after that instantly show all the array or probably i may preload with the same for each loop photos. I really do not know how to deal with it and maybe someone know how to do it without ugly animation?

Navigating Text box on a pdf is not working any more after iOS 13 - seems gestures issue using PDFKIT

I implemented a project I used PDFKIT to do some how adding a floating Textbox on a pdf and it can navigate by users touch on screen using GestureRecognizer to move and put where users decide to. it has worked perfectly before iOS 13, but after it, it does not give you the chance to move the text box and I tried many ways to solve it but all failed.
It seems that the problem somehow relates to GestureRecognizer but I am not sure, and also I really do not know how to fix it. I was working on this project on github https://github.com/kishikawakatsumi/BookReader and tried to expand it some how.
and here is my codes project, I am inserting the whole functions, I know it seems a little complicated. Really sorry about this. But if you think it might be from gesture recogniser, just look at the codes belong to these functions.
func getPDFFrame(todo: String)
{
let pdfSubVws = pdfView.subviews
print("subVws ",pdfSubVws)
for subVws in pdfSubVws
{
if (String(describing: subVws).range(of:"UIPageViewControllerContentView") != nil)
{
let pageVc = subVws.subviews
for subVws in pageVc
{
if (String(describing: subVws).range(of:"UIQueuingScrollView") != nil)
{
let QueueVc = subVws.subviews
// print("QueueVcQueueVc ", QueueVc)
for subVws in QueueVc
{
if (String(describing: subVws).range(of:"UIView") != nil)
{
let viewVc = subVws.subviews
print("\n\nviewVcVcQueueVc ", viewVc) //viewVcVcQueueVc []
for subVws in viewVc
{
if (String(describing: subVws).range(of:"UIView") != nil)
{
let SubviewVc = subVws.subviews
// print("\n\nSubviewVcSubviewVc ", SubviewVc)
for subVws in SubviewVc
{
if (String(describing: subVws).range(of:"UIScrollView") != nil)
{
let finalVw = subVws.subviews
// print("\n\nfinalVw ", finalVw)
//
for subVws in finalVw
{
if (String(describing: subVws).range(of:"UIView") != nil)
{
// print("subVwssubVws ", subVws)
let pagView = subVws.subviews
// pdfLandingView =
for subVws in pagView
{
// print("\n\n EndVwssubVws ", subVws)
if (String(describing: subVws).range(of:"PDFPageView") != nil)
{
let pageLandVw = subVws.subviews
print("\n\n WasVwssubVws ", pageLandVw)
// hideBars()
// Myedit()
for subVws in pageLandVw
{
if (String(describing: subVws).range(of:"UITextView") != nil)
{
print("dddddddd")
let txtVw = subVws as! UITextView
if todo == "firstResponder"
{
let rect = pdfView.currentPage?.bounds(for: .mediaBox)
usingHeightText = txtVw.frame.size.height
usingWidthText = txtVw.frame.size.width
let xPoint = txtVw.frame.origin.x
let yPoint = (rect?.height)! - (txtVw.frame.origin.y) - txtVw.frame.size.height
lastTextAnnoPoint = CGPoint(x: xPoint, y: yPoint)
findHavingTextAnnotation(annoPoint: CGPoint(x: xPoint, y: yPoint))
// txtVw.contentInset = UIEdgeInsetsMake(0, 10, 0, 0)
print("C_Sz ", txtVw.contentSize)
print("C_Off ", txtVw.contentOffset)
let widthMoveView = UIView(frame: CGRect(x: txtVw.frame.size.width - 20, y: 0, width: 20, height: txtVw.frame.size.height))
widthMoveView.backgroundColor = UIColor.brown.withAlphaComponent(0.0)
widthMoveView.tag = 333
let wdImgVw = UIImageView()
wdImgVw.frame.origin.x = 0
wdImgVw.frame.origin.y = 8
wdImgVw.frame.size.width = 20 // widthMoveView.frame.width
wdImgVw.frame.size.height = 20 // widthMoveView.frame.height
wdImgVw.contentMode = .scaleAspectFit
wdImgVw.image = UIImage(named: "widthLeftRight")
wdImgVw.layer.cornerRadius = 10
// wdImgVw.backgroundColor = UIColor.orange
widthMoveView.addSubview(wdImgVw)
txtVw.addSubview(widthMoveView)
//
let tapVw = UIPanGestureRecognizer(target: self, action: #selector(self.handleWidthTapVw(_:)))
widthMoveView.addGestureRecognizer(tapVw)
}
else
//....and here I am going to omit the other parts of my codes
and here I am going to omit the other parts of my codes because seems that the problem occurs in this line of code
for subVws in finalVw
and here other parts of my codes not sure you may need it or not
let linkAnn = PDFAnnotation.init(bounds: CGRect(x: 150, y: 450, width: 180, height: usingHeightText), forType: PDFAnnotationSubtype.widget, withProperties: nil)
linkAnn.widgetFieldType = .text
linkAnn.isMultiline = true
linkAnn.contents = "fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(AddTextCount)" //"\(AddTextCount)"
linkAnn.widgetStringValue = NSLocalizedString("placeholder", comment: "")
linkAnn.font = UIFont(name: usingFontName, size: CGFloat(usingFontSize))
linkAnn.fontColor = usingFontColor
linkAnn.backgroundColor = usingBGFontColor.withAlphaComponent(usingBGFontAlpha)
linkAnn.setValue("addtext\(AddTextCount)", forAnnotationKey: PDFAnnotationKey.name)
// print("linkAnn.cont ",linkAnn.contents)
let index = pdfDocument?.index(for: pdfView.currentPage!)
pdfView.document?.page(at: index!)?.addAnnotation(linkAnn)
var createdColorDict = [String : Any]()
createdColorDict["BGColor"] = usingBGFontColor
createdColorDict["BGOpacity"] = usingBGFontAlpha
textAnnoStoredDict["fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(AddTextCount)"] = createdColorDict
// pdfView.currentPage?.addAnnotation(linkAnn)
bottomColorView.isHidden = true
bottomColorView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
sideWidthHeightVw.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0)
sideWidthHeightVw.isHidden = true
barHideOnTapGestureRecognizer.isEnabled = false
hideBars()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow, object: nil)
//keyboardWillShow
Its hard for me to understand what could be the problem by looking at your code. Here's my high level suggestion:
1. Make a backup of your code first to make sure you can come back to your stable state.
2. Start cutting the code in half - eliminating half of the logic path each time. For example: Instead of using a PDF view, use a regular view with a text box (to find out if the problem is with the PDF view). Instead of using a UITextField, use just a UIView to see if it's a problem with UITextField.
Basically remove all the complexity gradually until you are left with a simple piece of code that allows you to move the text field.
Also: avoid having such long methods. I try to keep methods down to 30 lines max, and 2 levels of nesting max. Otherwise you will have more logic paths than you can maintain or understand...
You are also relying on strings for object types. This is fragile. Maybe there's another way to find the PDF View instead of crawling the whole view hierarchy for it, and checking strings? (They are not compiler checked, so any change in the future or change between OS / Third party versions will break your code).
If your text field doesn't move at all, try to remove all that math you're doing with the frame, and just get it to move using gesture recognizer to any coordinate (for example: 200, 200), just to see that something is holding the text field in place (like a constraint). Do you have constraints that can be holding it? Use the "View Inspector" to check and verify how the view is embedded and what's above / below it. Is there anything that could be intercepting touches to your gesture recognizer? Is it receiving touches and firing it's event? You need to describe more exactly what the problem is... Please refer to my answer here for things to check on the Gesture recognizer itself. UIPanGestureRecognizer is not working in iOS 13
Your view hierarchy is so complex with this PDF view that it's hard to say what could be happening with other Touch events inside it . (unless you understand exactly how the third party PDF View works). I would try to isolate the problem, whether it's related to the PDF view or not. Get it working in just a regular View first. Then work on the PDF view by using hitTest, and put a print statement there, to see who is competing for the HIT test.

Not getting selection from PDFView

I see somewhere this code for highlight selected text in pdf document:
let select = pdfView.currentSelection?.selectionsByLine()
//assuming for single-page pdf.
guard let page = select?.first?.pages.first else { return }
select?.forEach({ selection in
let highlight = PDFAnnotation(bounds: select.bounds(for: page), forType: .highlight, withProperties: nil)
highlight.endLineStyle = .square
highlight.color = UIColor.orange.withAlphaComponent(0.5)
page.addAnnotation(highlight)
})
for me ,
let select = pdfView.currentSelection?.selectionsByLine()
is always giving nil. where to put this code. I putting it in Gesture Recogniser Delegate methods.
Also it seems adding multiple annotation on page. Do we get single highlight annotation per selection on a page?

Multicolor Complication Text

I am creating a .graphicCorner ClockKit complication using the template CLKComplicationTemplateGraphicCornerTextImage. As mentioned in the Tech Talk Developing Complications for Apple Watch Series 4 it should be possible to combine multiple differently tinted Text Providers.
Unfortunately I can make it work.
Here's my code from ComplicationController.swift
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: #escaping (CLKComplicationTemplate?) -> Void) {
switch complication.family {
…
case .graphicCorner:
if #available(watchOSApplicationExtension 5.0, *) {
let template = CLKComplicationTemplateGraphicCornerStackText()
let firstTextProvider = CLKSimpleTextProvider(text: "first")
firstTextProvider.tintColor = UIColor.green
let secondTextProvider = CLKSimpleTextProvider(text: "second")
secondTextProvider.tintColor = UIColor.red
let thirdTextProvider = CLKSimpleTextProvider(text: "third")
thirdTextProvider.tintColor = UIColor.blue
template.outerTextProvider = firstTextProvider
template.innerTextProvider = CLKTextProvider.localizableTextProvider(withStringsFileFormatKey: "STRINGFORMAT", textProviders: [secondTextProvider, thirdTextProvider])
handler(template)
} else {
handler(nil) // Fallback on earlier versions
}
default:
handler(nil)
}
}
and the content of my ckcomplication.strings
"STRINGFORMAT" = "%# %#";
No text will show up. What am I doing wrong here? I appreciate any idea or working examples.
This seems to be the expected behaviour, at least for outerTextProvider:
The complication ignores the text provider’s tint color. It always displays the outer text as white.
outerTextProvider
It works for the innerTextProvider though, at least in here:
case .graphicCorner:
let graphicCorner = CLKComplicationTemplateGraphicCornerStackText()
let metarColor = UIColor.green
graphicCorner.outerTextProvider = CLKSimpleTextProvider(text: "EGLL")
graphicCorner.innerTextProvider = CLKSimpleTextProvider(text: "MVFR 27' ago")
graphicCorner.innerTextProvider.tintColor = metarColor ?? UIColor.white
let entry = CLKComplicationTimelineEntry(date: NSDate( as Date, complicationTemplate : graphicCorner)
timelineEntries.append(entry)
Screenshot
I ran into the same problem. I couldn't get CLKTextProvider.localizableTextProvider(withStringsFileFormatKey:, textProviders: ) combined with a ckcomplication.strings to work.
I ended up using this Objective-C category on CLKTextProvider.
It needed little customization for my own needs, but other than that it seems to work for me, I now get multi-coloured text in the inner ring.

NSimageView.image won't display an image in swift

I have an issue with a OSX application. I want it to display an image, so I create an NSImageView object, and linked it to my view controller. I then ceate a function that should load an image from a selected folder. I get the image url correctly an dtry to load the image onto the NSImageView but that doesn't work (with no rpeorted error). The image is a tiff file, and the isValid variable return false it seems...
imageAve is the name of the NSImageView outlet :
#IBOutlet weak var imageAve: NSImageView!
Here the code of the function in question :
func loadImage() { //load the tiff file
let image_url = String(describing: self.loadedtraces.tracefilesurls[self.indexSelected])
let image_url_cut = String(image_url[image_url.index(image_url.startIndex, offsetBy: 7)...image_url.index(image_url.endIndex, offsetBy: -8)] + "_ave_merged.tif")
if FileManager.default.fileExists(atPath: image_url_cut) { //test if the file exists and that works fine.
let image_average = NSImage(byReferencingFile: image_url_cut)
if (image_average?.isValid == false) {
self.alert.informativeText = "The image is invalid."
self.alert.alertStyle = .informational
self.alert.icon = alert_info_logo
self.alert.beginSheetModal(for: self.view.window!)
} else {
self.imageAve.needsDisplay = true
self.imageAve.image = image_average
}
} else {
self.alert.informativeText = "The average merge image file does not exist in the traces folder."
self.alert.alertStyle = .informational
self.alert.icon = alert_info_logo
self.alert.beginSheetModal(for: self.view.window!)
}
}
Thanks to everyone who might able to help !