Xcode 7.1, Swift 2 UIWebView Load Error - swift

I have a project that has a ViewController that loads a saved NSURL from memory. This NSURL is saved using NSCoding. When I run my app initially, my print log says:
Saved URL File:
file:///private/var/mobile/Containers/Data/Application/7939335F-C909-479E-A309-5AC833069A7B/Documents/Inbox/Pizza-2.pdf
Webview started Loading
Webview did finish load
It displays the PDF file just fine. When I run my app again a few minutes later, it won't display the PDF and it says:
Saved URL File:
file:///private/var/mobile/Containers/Data/Application/7939335F-C909-479E-A309-5AC833069A7B/Documents/Inbox/Pizza-2.pdf
Webview started Loading Webview fail with error Optional(Error
Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on
this server." UserInfo={NSUnderlyingError=0x14883f210 {Error
Domain=kCFErrorDomainCFNetwork Code=-1100 "The requested URL was not
found on this server."
UserInfo={NSErrorFailingURLStringKey=file:///private/var/mobile/Containers/Data/Application/7939335F-C909-479E-A309-5AC833069A7B/Documents/Inbox/Pizza-2.pdf,
NSLocalizedDescription=The requested URL was not found on this
server.,
NSErrorFailingURLKey=file:///private/var/mobile/Containers/Data/Application/7939335F-C909-479E-A309-5AC833069A7B/Documents/Inbox/Pizza-2.pdf}},
NSErrorFailingURLStringKey=file:///private/var/mobile/Containers/Data/Application/7939335F-C909-479E-A309-5AC833069A7B/Documents/Inbox/Pizza-2.pdf,
NSErrorFailingURLKey=file:///private/var/mobile/Containers/Data/Application/7939335F-C909-479E-A309-5AC833069A7B/Documents/Inbox/Pizza-2.pdf,
NSLocalizedDescription=The requested URL was not found on this
server.})
My code for the ViewController is:
class PDFItemViewController: UIViewController, UIWebViewDelegate {
// MARK: Properties
var file: PDFFile?
var incomingURL: NSURL!
#IBOutlet weak var background: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Set theme pic to back always
view.sendSubviewToBack(background)
let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 44, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
self.view.addSubview(myWebView)
myWebView.delegate = self
if let file = file {
incomingURL = file.url
print("Saved URL File: \(incomingURL)")
let request = NSURLRequest(URL: incomingURL!)
myWebView.loadRequest(request)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UIWebView Delegate
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print("Webview fail with error \(error)");
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return true
}
func webViewDidStartLoad(webView: UIWebView) {
print("Webview started Loading")
}
func webViewDidFinishLoad(webView: UIWebView) {
print("Webview did finish load")
}
}
'PDFFile' is an array of PDF Files. The NSURL is saved from an incoming PDF file the user can view from mail. It looks like it might not be saving? But why is it showing the file name if it's not saving? Thank you.
Update:
In my AppDelegate I have this code:
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
// Transfer incoming file to global variable to be read
if url != "" {
// Load from Mail App
incomingFileTransfer = url
incomingStatus = "Incoming"
}
return true
}
I've created a class called PDFFile.swift:
// Class for the saved PDF File, in this case a NSURL
class PDFFile: NSObject, NSCoding {
// MARK: Properties
var name: String
var url: NSURL
// MARK: Archiving Path
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("files")
// MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let urlKey = "url"
}
// MARK: Initialization
init?(name: String, url: NSURL) {
self.name = name
self.url = url
super.init()
if name.isEmpty {
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
aCoder.encodeObject(url, forKey: PropertyKey.urlKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
let url = aDecoder.decodeObjectForKey(PropertyKey.urlKey) as! NSURL
self.init(name: name, url: url)
}
}
When I view the incoming PDF file from mail, it loads in a separate UIWebView as such:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Incoming Emailed PDF from the 'Open-in' feature
if incomingFileTransfer != nil {
// Show incoming file
let request = NSURLRequest(URL: incomingFileTransfer!)
incomingView.loadRequest(request)
}
}
My save button points to an unwind on another View Controller as:
#IBAction func unwindToMainMenu(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? IncomingFileViewController, file = sourceViewController.file {
if let selectedIndexPath = fileTableNotVisible.indexPathForSelectedRow {
// Update an existing recipe.
pdfFiles[selectedIndexPath.row] = file
fileTableNotVisible.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
}
else {
// Add a new file
let newIndexPath = NSIndexPath(forRow: pdfFiles.count, inSection: 0)
// Add to pdf file array
pdfFiles.append(file)
// Adds new file to bottom of table
fileTableNotVisible.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
saveFiles()
}
}
// MARK: NSCoding
func saveFiles() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(pdfFiles, toFile: PDFFile.ArchiveURL.path!)
if !isSuccessfulSave {
print("Failed to save PDF file")
}
}

Related

How to programmatically save the content written in TextView to a text file when terminating the app?

I want to save the content of the text view when the user closes the app.
I used the following codes to do so, but I cannot get the up-to-date string of the textview when closing the app. So, the produced text file is blank.
How should I access to the NSTextView from AppDelegate to save its content?
ViewController.swift
import Cocoa
class ViewController: NSViewController {
static var textViewString: String = ""
#IBOutlet var textView: NSTextView!{
didSet{
ViewController.textViewString = textView.string
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// start with hidden and show after moving to the main screen
DispatchQueue.main.async {
//keep the window top
self.view.window?.level = .floating
//set up the main display as the display where window shows up
let screens = NSScreen.screens
var pos = NSPoint()
pos.x = screens[0].visibleFrame.midX
pos.y = screens[0].visibleFrame.midY
self.view.window?.setFrameOrigin(pos)
self.view.window?.zoom(self)
self.view.window?.level = .floating
//self.view.window?.backgroundColor = NSColor.white
//stop the user from moving window
self.view.window?.isMovable = false
//disable resizable mode
self.view.window?.styleMask.remove(.resizable)
self.view.window?.setIsVisible(true)
}
//set up font for the reflectionForm
textView.font = NSFont.systemFont(ofSize: 30)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func saveTextViewString(){
if let documentDirectoryFileURL = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last {
let fileName = "savedText.txt"
let targetTextFilePath = documentDirectoryFileURL + "/" + fileName
do {
try ViewController.textViewString.write(toFile: targetTextFilePath, atomically: true, encoding: String.Encoding.utf8)
print("successfully recorded: \(ViewController.textViewString.description) at \(fileName.utf8CString)")
} catch let error as NSError {
print("failed to write: \(error)")
}
}
}
}
AppDelegate.swift
import Cocoa
#main
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
//save the string in the textview into a text file
ViewController().saveTextViewString()
}
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
}
Thank you for the #jnpdx's comments, I was able to solve this by just declaring ViewController in the AppDelegate by stating var viewController: ViewController!
ViewController.swift
import Cocoa
class ViewController: NSViewController {
#IBOutlet var textView: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// start with hidden and show after moving to the main screen
DispatchQueue.main.async {
//keep the window top
self.view.window?.level = .floating
//set up the main display as the display where window shows up
let screens = NSScreen.screens
var pos = NSPoint()
pos.x = screens[0].visibleFrame.midX
pos.y = screens[0].visibleFrame.midY
self.view.window?.setFrameOrigin(pos)
self.view.window?.zoom(self)
self.view.window?.level = .floating
//self.view.window?.backgroundColor = NSColor.white
//stop the user from moving window
self.view.window?.isMovable = false
//disable resizable mode
self.view.window?.styleMask.remove(.resizable)
self.view.window?.setIsVisible(true)
}
//set up font for the reflectionForm
textView.font = NSFont.systemFont(ofSize: 30)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func saveTextViewString(){
if let documentDirectoryFileURL = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last {
let fileName = "savedText.txt"
let targetTextFilePath = documentDirectoryFileURL + "/" + fileName
do {
try textView.string.write(toFile: targetTextFilePath, atomically: true, encoding: String.Encoding.utf8)
print("successfully recorded: \(textView.string.description) at \(fileName.utf8CString)")
} catch let error as NSError {
print("failed to write: \(error)")
}
}
}
}
AppDelegate.swift
import Cocoa
#main
class AppDelegate: NSObject, NSApplicationDelegate {
//connect viewController with ViewController
var viewController: ViewController!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
//save the string in the textview into a text file
viewController.saveTextViewString()
}
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
}

NSCocoaErrorDomain Code=257 File Permission

While trying to get a file inside a Swift UI App using a UIViewControllerRepresentable wrapping an UIDocumentPickerViewController, I ran into a very weird behaviour:
Running the app on the simulator works as expected. Running the app on a physical device however would not return the files. Instead it would throw this error: Error Domain=NSCocoaErrorDomain Code=257 "The file “grile.doc” couldn’t be opened because you don’t have permission to view it."
Debugging, I managed to find that the code block causing this error to be thrown on the physical device isn't the actual accessing of the file, instead it's trying to get the file size that throws.
What am I doing wrong here, that makes this Representable work just fine on a simulator but not work on a physical device?
I have already tried using the FileManager approach to get file size, same thing happens. I also tried copying the file to a temp location with FileManager, that also throws the same error.
import Foundation
import SwiftUI
import UniformTypeIdentifiers
struct FilePicker: UIViewControllerRepresentable {
// MARK: - Properties
var didPickFileURL: ((URL) -> Void)
var didPickFileOverFileSizeLimit: (() -> Void)
// MARK: - UIViewController Wrapper Methods
func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
let picker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType("public.item")!])
picker.allowsMultipleSelection = false
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
return FilePicker.Coordinator(parent: self)
}
// MARK: - Coordinator
class Coordinator: NSObject, UIDocumentPickerDelegate {
// MARK: - Coordinator Properties
var parent: FilePicker
// MARK: - Coordinator Init
init(parent: FilePicker) {
self.parent = parent
}
// MARK: - Coordinator UIDocument Delegate
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first else { return }
do {
let resources = try url.resourceValues(forKeys:[.fileSizeKey])
let fileSize = Double(resources.fileSize!)
// check if the file size is bigger than the limit per attachment
if fileSize.convertBytesToMegabytes() < 10 {
self.parent.didPickFileURL(url)
} else {
self.parent.didPickFileOverFileSizeLimit()
}
} catch {
print("Error: \(error)")
}
}
}
}
The conversion extension:
extension Double {
func convertBytesToMegabytes() -> Double {
let kilobytes = self / 1024
let megabytes = kilobytes / 1024
return megabytes
}
}
I've had issues as well. If you look at the URL to your document you might try:
url.startAccessingSecurityScopedResource()
If that returns true you will also need to call:
url.stopAccessingSecurityScopedResource()

didInititate method for Spotify IOS SDK is not calling even though called sessionManager.initiateSession()

I'm going through Spotify's authentication process and am requesting the scopes appRemoteControl for my app to control music and userReadCurrentlyPlaying for current song. I set up everything from the SPTConfiguration, SPTSessionManager, and SPTAppRemote, and their required delegate methods (SPTAppRemoteDelegate, SPTSessionManagerDelegate, SPTAppRemotePlayerStateDelegate) as well as initiating a session with the requested scopes whenever the user presses a button but I can't get the method
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
to trigger. The authentication process fully works as it goes into my spotify app and returns back to my application and plays a song from the configuration.playURI = "" , however, the method above never is called. I followed the spotify demo project but still does not work. Here is my full code
class LogInViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
let spotifyClientID = Constants.clientID
let spotifyRedirectURL = Constants.redirectURI
let tokenSwap = "https://***********.glitch.me/api/token"
let refresh = "https://***********.glitch.me/api/refresh_token"
lazy var configuration: SPTConfiguration = {
let configuration = SPTConfiguration(clientID: spotifyClientID, redirectURL: URL(string: "Lyrically://callback")!)
return configuration
}()
lazy var sessionManager: SPTSessionManager = {
let manager = SPTSessionManager(configuration: configuration, delegate: self)
if let tokenSwapURL = URL(string: tokenSwap), let tokenRefreshURL = URL(string: refresh) {
self.configuration.tokenSwapURL = tokenSwapURL
self.configuration.tokenRefreshURL = tokenRefreshURL
self.configuration.playURI = ""
}
return manager
}()
lazy var appRemote: SPTAppRemote = {
let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug)
appRemote.delegate = self
return appRemote
}()
#IBAction func logIn(_ sender: UIButton) {
let requestedScopes: SPTScope = [.appRemoteControl, .userReadCurrentlyPlaying]
sessionManager.initiateSession(with: requestedScopes, options: .default)
}
}
extension LogInViewController: SPTAppRemotePlayerStateDelegate {
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
print("state changed")
}
}
extension LogInViewController: SPTAppRemoteDelegate {
func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
print("connected")
appRemote.playerAPI?.delegate = self
appRemote.playerAPI?.subscribe(toPlayerState: { (success, error) in
if let error = error {
print("Error subscribing to player state:" + error.localizedDescription)
}
})
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
print("failed")
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
print("disconnected")
}
}
extension LogInViewController: SPTSessionManagerDelegate {
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
print("failed",error)
}
}
Figured it out. Had to get a hold of the sessionManager from the LogInViewController by making an instance of it
lazy var logInVC = LogInViewController()
then added this line of code into the openURLContexts method in scene delegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
print("Opened url")
guard let url = URLContexts.first?.url else {
return
}
logInVC.sessionManager.application(UIApplication.shared, open: url, options: [:])
}

MLMediaLibrary - Displaying the Photo Library -Swift Code Wrong - macOS

Trying to show photos from the Photo Library. The Apple Sample Code below does not work properly. It doesn't wait for the notifications but tries to launch the collection view which crashes at Number of Items in Section because there is no photo data to show.
Thanks for any help from you Swift guru's out there!
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ViewController` class is a subclass to NSViewController responsible for managing the app's content.
*/
import Cocoa
import MediaLibrary
class IconViewBox : NSBox {
override func hitTest(_ aPoint: NSPoint) -> NSView? {
// Don't allow any mouse clicks for subviews in this NSBox.
return nil
}
}
// MARK: -
class ViewController: NSViewController, NSCollectionViewDelegate {
// MARK: - Types
// Keys describing the dictionary for each photo loaded.
private struct ItemKeys {
static let imageKey = "icon"
static let nameKey = "name"
}
// MLMediaLibrary property values for KVO.
private struct MLMediaLibraryPropertyKeys {
static let mediaSourcesKey = "mediaSources"
static let rootMediaGroupKey = "rootMediaGroup"
static let mediaObjectsKey = "mediaObjects"
static let contentTypeKey = "contentType"
}
// MARK: - Properties
/**
The KVO contexts for `MLMediaLibrary`.
This provides a stable address to use as the `context` parameter for KVO observation methods.
*/
private var mediaSourcesContext = 1
private var rootMediaGroupContext = 2
private var mediaObjectsContext = 3
private var photoSize = CGSize(width: 168, height: 145)
// Contains an array of dictionaries describing each photo (refer to ItemKeys for key/values).
#IBOutlet weak var arrayController: NSArrayController!
#IBOutlet weak var collectionView: NSCollectionView!
#IBOutlet private weak var noPhotosLabel: NSTextField!
#IBOutlet private weak var activityIndicator: NSProgressIndicator!
// MLMediaLibrary instances for loading the photos.
private var mediaLibrary: MLMediaLibrary!
private var mediaSource: MLMediaSource!
private var rootMediaGroup: MLMediaGroup!
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
print ("VDL1...................")
// Start progress indicator in case fetching the photos from the photo library takes time.
self.activityIndicator.isHidden = false
self.activityIndicator.startAnimation(self)
self.collectionView.minItemSize = self.photoSize
self.collectionView.maxItemSize = self.photoSize
self.arrayController.setSelectionIndex(-1) // No selection to start out with.
// Setup the media library to load only photos, don't include other source types.
let options: [String : AnyObject] =
[MLMediaLoadSourceTypesKey: MLMediaSourceType.image.rawValue as AnyObject,
MLMediaLoadIncludeSourcesKey: [MLMediaSourcePhotosIdentifier, MLMediaSourceiPhotoIdentifier] as AnyObject]
// Create our media library instance to get our photo.
mediaLibrary = MLMediaLibrary(options: options)
// We want to be called when media sources come in that's available (via observeValueForKeyPath).
self.mediaLibrary.addObserver(self,
forKeyPath: MLMediaLibraryPropertyKeys.mediaSourcesKey,
options: NSKeyValueObservingOptions.new,
context: &mediaSourcesContext)
if (self.mediaLibrary.mediaSources != nil) {
print ("VDL2...................")
} // Reference returns nil but starts the asynchronous loading.
}
deinit {
// Make sure to remove us as an observer before "mediaLibrary" is released.
self.mediaLibrary.removeObserver(self, forKeyPath: MLMediaLibraryPropertyKeys.mediaSourcesKey, context:&mediaSourcesContext)
}
// MARK: - NSCollectionViewDataSource
func numberOfSectionsInCollectionView(_ collectionView: NSCollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
let photos = self.arrayController.arrangedObjects as! NSArray
return photos.count
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "IconItem"), for:indexPath)
let photos = self.arrayController.arrangedObjects as! NSArray
let iconInfo = photos[(indexPath as NSIndexPath).item]
item.representedObject = iconInfo
return item
}
// MARK: - NSCollectionViewDelegate
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
if let itemIndexPath = indexPaths.first {
let photos = self.arrayController.arrangedObjects as! NSArray
let itemDict = photos[((itemIndexPath as NSIndexPath).item)] as! NSDictionary
if let itemTitle = itemDict[ItemKeys.nameKey] as? String {
if (itemTitle.characters.count > 0) {
print("selected photo: '\(itemTitle)'")
}
else {
print("selected photo: <no title>")
}
}
}
}
// MARK: - Utilities
/// Helps to make sure the media object is the photo format we want.
private func isValidImage(_ mediaObject: MLMediaObject) -> Bool {
var isValidImage = false
let attrs = mediaObject.attributes
let contentTypeStr = attrs[MLMediaLibraryPropertyKeys.contentTypeKey] as! String
// We only want photos, not movies or older PICT formats (PICT image files are not supported in a sandboxed environment).
if ((contentTypeStr != kUTTypePICT as String) && (contentTypeStr != kUTTypeQuickTimeMovie as String))
{
isValidImage = true
}
return isValidImage
}
/// Obtains the title of the MLMediaObject (either the meta name or the last component of the URL).
func imageTitle(_ fromMediaObject: MLMediaObject) -> String {
guard let title = fromMediaObject.attributes["name"] else {
return fromMediaObject.url!.lastPathComponent
}
return title as! String
}
// MARK: - Photo Loading
/// Observer for all key paths returned from the MLMediaLibrary.
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print ("Observe1...................")
if (keyPath == MLMediaLibraryPropertyKeys.mediaSourcesKey && context == &mediaSourcesContext && object! is MLMediaLibrary) {
// The media sources have loaded, we can access the its root media.
if let mediaSource = self.mediaLibrary.mediaSources?[MLMediaSourcePhotosIdentifier] {
self.mediaSource = mediaSource
}
else if let mediaSource = self.mediaLibrary.mediaSources?[MLMediaSourceiPhotoIdentifier] {
self.mediaSource = mediaSource
}
else {
print ("Observe2...................")
// Can't find any media sources.
self.noPhotosLabel.isHidden = false
// Stop progress indicator.
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimation(self)
return // No photos found.
}
// Media Library is loaded now, we can access mediaSource for photos
self.mediaSource.addObserver(self,
forKeyPath: MLMediaLibraryPropertyKeys.rootMediaGroupKey,
options: NSKeyValueObservingOptions.new,
context: &rootMediaGroupContext)
// Obtain the media grouping (reference returns nil but starts asynchronous loading).
if (self.mediaSource.rootMediaGroup != nil) {}
}
else if (keyPath == MLMediaLibraryPropertyKeys.rootMediaGroupKey && context == &rootMediaGroupContext && object! is MLMediaSource) {
print ("Observe3...................")
// The root media group is loaded, we can access the media objects.
// Done observing for media groups.
self.mediaSource.removeObserver(self, forKeyPath: MLMediaLibraryPropertyKeys.rootMediaGroupKey, context:&rootMediaGroupContext)
self.rootMediaGroup = self.mediaSource.rootMediaGroup
self.rootMediaGroup.addObserver(self,
forKeyPath: MLMediaLibraryPropertyKeys.mediaObjectsKey,
options: NSKeyValueObservingOptions.new,
context: &mediaObjectsContext)
// Obtain the all the photos, (reference returns nil but starts asynchronous loading).
if (self.rootMediaGroup.mediaObjects != nil) {}
}
else if (keyPath == MLMediaLibraryPropertyKeys.mediaObjectsKey && context == &mediaObjectsContext && object! is MLMediaGroup) {
print ("Observe4...................")
// The media objects are loaded, we can now finally access each photo.
// Done observing for media objects that group.
self.rootMediaGroup.removeObserver(self, forKeyPath: MLMediaLibraryPropertyKeys.mediaObjectsKey, context:&mediaObjectsContext)
// Stop progress indicator since we know if we have photos (or not).
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimation(self)
let mediaObjects = self.rootMediaGroup.mediaObjects
if (mediaObjects != nil && mediaObjects!.count > 0) {
print ("Observe5...................")
// Add photos to the array, to be used in our NSCollectionView.
for mediaObject in mediaObjects! {
if (self.isValidImage(mediaObject)) { // Make sure the media object is a photo.
let title = self.imageTitle(mediaObject)
if let image = NSImage.init(contentsOf: mediaObject.thumbnailURL!) {
let iconItem : Dictionary = [ItemKeys.imageKey: image, ItemKeys.nameKey: title] as [String : Any]
self.arrayController.addObject(iconItem)
}
}
}
self.collectionView.reloadData()
}
else {
// No photos available.
self.noPhotosLabel.isHidden = false
}
self.rootMediaGroup = nil // We are done with this.
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
NSCollectionViewDataSource delegate is missing
class ViewController: NSViewController, NSCollectionViewDelegate, NSCollectionViewDataSource
Next you need to fix these methods: 'numberOfSectionsInCollectionView' has been renamed to 'numberOfSections(in:)' 'collectionView(:itemForRepresentedObjectAtIndexPath:)' has been renamed to 'collectionView(:itemForRepresentedObjectAt:)'

iOS/Swift: QLPreviewController shows blank page in iOS11

I've tried use QLPreviewController for file(.txt, .pdf, .docx, .xlsx, etc.) preview in my iOS project, but it is not working well in iOS 11: it shows blank page whatever use device or simulator. In iOS 10.3.1(simulator) it is working well, and everything is fine.
The below is the detail informations:
Environment:
Xcode version: 8.3.3, 9.0.1
Device: iPhone 7 Plus, Simulator
iOS version: 11.0.3(iPhone 7 Plus), 10.3.1(Simulator), 11.0.1(Simulator)
Swift version: 3.1/3.2
Code
import UIKit
import QuickLook
class QuickViewController: UIViewController {
var url: String!
var filePath: URL!
var msg: Message! {
didSet {
url = msg.content
// create document folder url
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
filePath = documentsURL.appendingPathComponent((msg.content as NSString).lastPathComponent)
}
}
#IBOutlet weak var contentView: UIView!
// MARK: - Initialisation
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loafFile()
}
func loafFile() {
if FileManager.default.fileExists(atPath: filePath.path) {
quickLookFile()
} else {
AppManager_Inst.download(url: "\(url!)", destinationUrl: filePath, completion: { [unowned self](succeed, msg) in
if succeed {
self.quickLookFile()
} else {
print(msg)
}
})
}
}
func quickLookFile() {
print(filePath.path)
/// Trying to read the file via FileManager to check if the filePath is correct or not
let data = FileManager.default.contents(atPath: filePath.path)
print(data)
if QLPreviewController.canPreview(filePath as NSURL) {
let QLController = QLPreviewController()
QLController.delegate = self
QLController.dataSource = self
QLController.view.frame = self.contentView.frame
self.view.addSubview(QLController.view)
} else {
print("file cannot to preview")
}
}
}
extension QuickViewController: QLPreviewControllerDataSource, QLPreviewControllerDelegate {
// QLPreviewControllerDataSource
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return filePath as NSURL
}
// QLPreviewControllerDelegate
func previewController(_ controller: QLPreviewController, shouldOpen url: URL, for item: QLPreviewItem) -> Bool {
return true
}
}
I'm not sure what I missing or something wrong here, please help.
p.s.: I'll trying the code with iPhone 5c(iOS 10.3.1) later, and the result should update to here once I've done it.
You did not add the current viewController as the parent class of the QLPreviewController()
Just add QLController.didMove(toParentViewController: self) after adding it to the self.view
I think this should solve your issue.