Posts

Post marked as solved
1 Replies
522 Views
I'm trying to export a document file. It contains a codable struct named NoteGroup. struct NoteGroup: Codable { let id: UUID let name: String let createAt: Date let children: [NoteChild] init(id: UUID = .init(), name: String = "", createAt: Date = .init(), children: [NoteChild]) { self.id = id self.name = name self.createAt = createAt self.children = children } } , which contains another object named NoteChild. I have a FileDocument struct as follows. import SwiftUI import UniformTypeIdentifiers struct Document: FileDocument { var document: NoteGroup static var readableContentTypes = [UTType.frogType] init(document: NoteGroup = NoteGroup(children: [NoteChild(id: UUID(), name: "", createAt: Date())])) { self.document = document } init(configuration: ReadConfiguration) throws { self.init() } func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { do { let data = try getDocumentData() let jsonFileWrapper = FileWrapper(regularFileWithContents: data) let filename = "Note.frog" jsonFileWrapper.filename = filename let fileWrapper = FileWrapper(directoryWithFileWrappers: [filename: jsonFileWrapper]) return fileWrapper } catch { throw error } } private func getDocumentData() throws -> Data { let encoder = JSONEncoder() do { let data = try encoder.encode(document) return data } catch { throw error } } } extension UTType { public static let frogType = UTType(exportedAs: "com.example.frog") } And I export a file like the following. import SwiftUI import UniformTypeIdentifiers struct ContentView: View { @State private var showingExporter = false @State var doc = Document() var body: some View { VStack { Button("Tap to export") { showingExporter.toggle() } .fileExporter( isPresented: $showingExporter, document: doc, contentType: .frogType ) { result in switch result { case .success(let file): print(file) case .failure(let error): print(error) } } }.onAppear { doc = Document(document: NoteGroup(id: UUID(), name: "Kyle", createAt: Date(), children: [NoteChild(id: UUID(), name: "Nancy", createAt: Date())])) } } } Well, I have read this topic. And I've watched this video about Uniform Type Identifiers. Thanks to the video, I am able to export a file. Yet, I end up with a folder (Frog.frog), not a packaged file. There is a JSON file in it, though. What am I doing wrong? It's for iOS. La vida no es facil. Muchos thankos.
Posted
by Tomato.
Last updated
.
Post marked as solved
1 Replies
396 Views
I use the ForEach enumeration to list a View horizontally. And I get the following picture. So far, so good... If I select the 5th object or 6th one, something odd (< More) appears. I don't know where it comes from. I have never seen it before. How does it happen? I wonder how I can remove it? I have searched the net for a clue to no avail. I don't even know how to describe it. The following is my code. import SwiftUI struct ContentView: View { @State var selectedTab = 0 @State var addTapped = false @State var refresh = false @State var people = [ Person(name: "Alice", systemImage: "person.circle.fill"), Person(name: "Jane", systemImage: "person.circle.fill"), Person(name: "Dave", systemImage: "person.circle.fill"), Person(name: "Susan", systemImage: "person.circle.fill"), Person(name: "Robert", systemImage: "person.circle.fill"), Person(name: "Daniel", systemImage: "person.circle.fill") ] var body: some View { VStack(alignment: .leading, spacing: 0) { ScrollView(.horizontal) { HStack(spacing: 20) { ForEach(0..<people.count, id: \.self) { num in VStack { let person = people[num] Image(systemName: person.systemImage) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 32) Text(person.name) .fixedSize() } .foregroundColor(selectedTab == num ? Color.blue : Color.gray) .onTapGesture { self.selectedTab = num } } } }.padding(.horizontal, 10) Spacer() .frame(height: 2) Rectangle().fill(.gray) .frame(height: 1) TabView(selection: $selectedTab) { ForEach(0..<people.count, id: \.self) { num in let person = people[num] Text(person.name) .tag(person.id) } } } } } struct Person: Identifiable { let id = UUID() let name: String let systemImage: String } Muchos thankos.
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
2 Replies
679 Views
I have followed a tutorial written by Hacking with Swift ( https://www.hackingwithswift.com/books/ios-swiftui/how-to-combine-core-data-and-swiftui) about Core Data in SwiftUI. The Entity name is Student. And it has two properties: name (String), id (UUID). And the following is my code. import SwiftUI struct CoreView: View { @Environment(\.managedObjectContext) var managedObject @FetchRequest(sortDescriptors: []) var students: FetchedResults<Student> var body: some View { VStack { List(students) { student in Text(student.name ?? "Unknown") } Button { let firstNames = ["Gary", "Harry", "Elane", "Ray", "Nancy", "Jim", "Susan"] let lastNames = ["Johns", "McNamara", "Potter", "Thompson", "Hampton"] if let selectedFirstName = firstNames.randomElement(), let selectedLastName = lastNames.randomElement() { let newStudent = Student(context: managedObject) newStudent.id = UUID() newStudent.name = "\(selectedFirstName) \(selectedLastName)" try? managedObject.save() } } label: { Text("Add") } } } } struct CoreView_Previews: PreviewProvider { static var previews: some View { CoreView() .environmentObject(DataController()) } } If I list all records and then add a new student to the list, the app will insert the last addition at a random row. I wonder if I can order these records by the creation date? Muchos thankos
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
0 Replies
803 Views
I have the following lines of code to list some music titles from iTunes music. The code is 100% reproducible. import SwiftUI struct MusicView: View { @StateObject var viewModel = ViewModel() var body: some View { MusicListView(viewModel: viewModel) } } struct MusicListView: View { @ObservedObject var viewModel: ViewModel var body: some View { NavigationView { List(viewModel.results, id: \.self) { result in VStack(alignment: .leading) { Text("Track ID: \(result.trackId)") Text("Track name: \(result.trackName)") } } .task { do { try await viewModel.fetchMusic() } catch SessionError.badURL { print("Bad URL") } catch SessionError.invalidHTTPResponse { print("Invalid HTTP response") } catch SessionError.error(let err) { print("Error: \(err)") } catch { print("\(error.localizedDescription)") } } .navigationTitle("Music") } } } class ViewModel: ObservableObject { @Published var results: [Result] = [] func fetchMusic() async throws { guard let url = URL(string: "https://itunes.apple.com/search?term=classical+music&entity=song") else { throw SessionError.badURL } let urlRequest = URLRequest(url: url, timeoutInterval: 0.00) // <<<<<<<<<<<<< URLSession.shared.dataTask(with: urlRequest) { data, response, error in do { guard let data = data, error == nil else { throw SessionError.noData } guard let httpResponse = response as? HTTPURLResponse else { throw SessionError.invalidHTTPResponse } switch httpResponse.statusCode { case 200: let res = try JSONDecoder().decode(Response.self, from: data) DispatchQueue.main.async { self.results = res.results } case 400...499: throw SessionError.badURL default: fatalError() break } } catch { print(error.localizedDescription) } } .resume() } } struct Response: Codable { let resultCount: Int let results: [Result] } struct Result: Codable, Hashable { var trackId: Int var trackName: String var collectionName: String } enum SessionError: Error { case badURL case noData case decoding case invalidHTTPResponse case badRequest(statusCode: Int) case redirection(statusCode: Int) case server(statusCode: Int) case error(String) } As you see in the screenshot, I get some music titles listed. My question is why I get a list when in fact I have the URLRequest's timeout value set to 0.00? I haven't run it with an actual device. As far as I use an iPhone simulator, regardless of the timeout value that I set, I get data downloaded. I wonder why? Muchos thankos for reading
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
0 Replies
309 Views
Oh, boy... Xcode has become more and more difficult to deal with. Today, I've dowloaded Version 15.0 beta 4. It took my 2019 iMac with 64 GB of RAM some 20 minutes just to launch an iPhone 14 Simulator and to let me see the home screen. Xcode takes 3 or 4 minutes to run code after I change just one line. I only have some 30 lines of code in total. It's a truly disappointing update. I wish they stop adding unnecessary features like code-folding animation to slow things down. import UIKit class ViewController: UIViewController { private let photoView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(systemName: "airplane") //imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemYellow view.addSubview(photoView) NSLayoutConstraint.activate([ photoView.centerXAnchor.constraint(equalTo: view.centerXAnchor), photoView.centerYAnchor.constraint(equalTo: view.centerYAnchor), photoView.widthAnchor.constraint(equalToConstant: 200), photoView.heightAnchor.constraint(equalToConstant: 200) ]) DispatchQueue.main.asyncAfter(deadline: .now() + 3) { self.runAirplaneAnimation() } } func runAirplaneAnimation() { photoView.addSymbolEffect(.pulse, animated: true) } }
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
0 Replies
588 Views
I have some lines of code below where I can make multiple selections. import SwiftUI struct ContentView: View { @State private var selectedUsers: Set<String> = [] @State var users = ["Susan", "Kate", "Natalie", "Kimberly", "Taylor", "Sarah", "Nancy", "Katherine", "Nicole", "Linda", "Jane", "Mary", "Olivia", "Barbara"] var body: some View { VStack { List(selection: $selectedUsers) { ForEach(users, id: \.self) { user in Text(user) } } .environment(\.editMode, .constant(.active)) } } } So the blue selection symbol appears as shown in the screenshot above. That's good. But that's not what I'm after. I just want to select one row at a time. import SwiftUI struct ContentView: View { @State var selectedUser: String? @State var users = ["Susan", "Kate", "Natalie", "Kimberly", "Taylor", "Sarah", "Nancy", "Katherine", "Nicole", "Linda", "Jane", "Mary", "Olivia", "Barbara"] var body: some View { VStack { List(selection: $selectedUser) { ForEach(users, id: \.self) { user in Text(user) } } .environment(\.editMode, .constant(.active)) } } } In the lines of code above, I only let myself select one row at a time. And I don't get the blue selection symbol. I wonder why? I find two or three websites where they have similar lines of code and where they select one row at a time. And they have the blue selection symbol. Why don't I get it? Mucho thankos for reading.
Posted
by Tomato.
Last updated
.
Post marked as solved
1 Replies
353 Views
Drawing a pie isn't difficult if I do it with Path. import SwiftUI struct ContentView8: View { var body: some View { PieSlice(start: .degrees(-90), end: .degrees(120)) .fill(.pink) } } struct PieSlice: Shape { let start: Angle let end: Angle func path(in rect: CGRect) -> Path { var path = Path() let center = CGPoint(x: rect.midX, y: rect.midY) path.move(to: center) path.addArc(center: center, radius: rect.midX, startAngle: start, endAngle: end, clockwise: false) return path } } Actually, I want to animate this pie such that it will gradually deploy starting at -90 degrees. In the code above, I suppose I cannot animate the pie because the PieSlice guy isn't a View. Or can I? If I can't, is there an alternative way of drawing a pie so that I can animate it? Thanks a million. Señor Tomato Source Hostage Negotiator at Tomato Source Association of North America
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
0 Replies
625 Views
I've been trying to save a selected color with UserDefaults from UIColorPickerViewController. But I run into a color space fiasco. Anyway, here come my lines of code. class ViewController: UIViewController, UIColorPickerViewControllerDelegate { @IBOutlet weak var imageView: UIImageView! @IBAction func selectTapped(_ sender: UIButton) { let picker = UIColorPickerViewController() picker.delegate = self picker.selectedColor = .yellow picker.supportsAlpha = false present(picker, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let color = UserDefaultsUIColor.shared.readColor(key: "MyColor") { print("Color being read: \(color)") } } func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) { let color = viewController.selectedColor print("Selected color: \(color)") UserDefaultsUIColor.shared.saveColor(color: viewController.selectedColor, key: "MyColor") } func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) { imageView.backgroundColor = viewController.selectedColor } } class UserDefaultsUIColor { static let shared = UserDefaultsUIColor() func saveColor(color: UIColor, key: String) { let userDefaults = UserDefaults.standard do { let data = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) as NSData? userDefaults.set(data, forKey: key) } catch { print("Error UserDefaults: \(error.localizedDescription)") } } func readColor(key: String) -> UIColor? { let userDefaults = UserDefaults.standard if let data = userDefaults.data(forKey: key) { do { if let color = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: data) { return color } } catch { print("Error UserDefaults") } } return nil } } I first start out with a yellow color (UIColor.yellow). And I select a color whose RGB values are 76, 212, 158, respectively. And the color picker guy returns the following. kCGColorSpaceModelRGB 0.298039 0.831373 0.619608 1 And I get the following in reading the saved color data object. UIExtendedSRGBColorSpace -0.270778 0.84506 0.603229 1 How can I save and read color data objects consistently? I could specify a color space when I save a color. But it doesn't go well. Muchos thankos Señor Tomato de Source
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
0 Replies
434 Views
I am just playing with NSTextList by creating a sample iOS app. The following is my code. import UIKit class ViewController: UIViewController { lazy var textView: UITextView = { let textView = UITextView() textView.text = "" textView.contentInsetAdjustmentBehavior = .automatic textView.backgroundColor = .white textView.font = UIFont.systemFont(ofSize: 20.0) textView.textColor = .black textView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ textView.widthAnchor.constraint(equalToConstant: 600.0), textView.heightAnchor.constraint(equalToConstant: 600.0) ]) return textView }() lazy var button: UIButton = { let button = UIButton() button.setTitle("End list", for: .normal) button.setTitleColor(.white, for: .normal) button.setTitleColor(.lightGray, for: .highlighted) button.backgroundColor = .black button.layer.cornerRadius = 8.0 button.addTarget(self, action: #selector(fixTapped), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ button.widthAnchor.constraint(equalToConstant: 100.0), button.heightAnchor.constraint(equalToConstant: 42.0) ]) return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBlue view.addSubview(textView) view.addSubview(button) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tapGesture) NSLayoutConstraint.activate([ textView.centerXAnchor.constraint(equalTo: view.centerXAnchor), textView.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: view.centerXAnchor), button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20.0) ]) let list = NSTextList(markerFormat: .diamond, options: 0) list.startingItemNumber = 1 let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.textLists = [list] let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24.0)] let attributedStr = NSMutableAttributedString(string: "\n\n\n\n\n", attributes: attributes) textView.textStorage.setAttributedString(attributedStr) } @objc func fixTapped() { } @objc func dismissKeyboard() { view.endEditing(true) } } When the app launches itself, I get 5 lines of diamond guys as shown in the following screenshot. If I keep pressing the delete key with a connected keyboard, the list will be gone as shown below. But if I press the RETURN key several times, the diamond list will come back as shown below. So how can I end this June TextList madness? In code, I have the dismissKeyboard function if I can end this madness programmatically. Thanks, Señor Tomato Spaghetti Chief Janitor at Southeastern Tomato Spaghetti Trade Association
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
1 Replies
553 Views
I have a simple app that implements a custom URL scheme. When I enter the scheme for my app in Safari, the app will launch itself. So far, so good... Now, when I initiate the app switcher, I have my app and the web browser (Safari). Is there a way of not showing them in the app switcher? Or can I at least stop the web browser from appearing in the app switcher? Is it even possible for me to terminate Safari programmatically from my app, provided that that is not going to violate the app store guidelines? Thanks.
Posted
by Tomato.
Last updated
.
Post marked as solved
1 Replies
299 Views
I'm using the custom URL scheme to open my app through Safari. When the app appears, the status bar shows 'Safari' at the top-left corner. Is there a way of stopping the app from showing Safari's name? I don't want the user to tap the name and go back to Safari. There is nothing special in my SceneDelegate. So I wonder if it's probably the matter of settings in the Settings app? Thanks.
Posted
by Tomato.
Last updated
.
Post not yet marked as solved
0 Replies
612 Views
I didn't know that Settings Bundle exists till two days ago. Anyway, I've tested it with a simple example. As shown in the screenshot below, I have one group, one text field, one slider and two toggle buttons. I am able to read the values from all of them except the slider. I wonder if it's a bug? I'm using Xcode 14.2. In the following code, the app won't go inside the if clause for the PSSliderSpecifier key. import UIKit class ViewController: UIViewController { // MARK: - Life cyle override func viewDidLoad() { super.viewDidLoad() let defaultValues = [String: AnyObject]() UserDefaults.standard.register(defaults: defaultValues) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) /* settings */ fetchSettingBundleData() } @objc func fetchSettingBundleData() { let userDefaults = UserDefaults.standard if let settingsURL = Bundle.main.url(forResource: "Root", withExtension: "plist", subdirectory: "Settings.bundle"), let settings = NSDictionary(contentsOf: settingsURL), let preferences = settings["PreferenceSpecifiers"] as? [NSDictionary] { var defaultsToRegister = [String: Any]() for preferenceSpecification in preferences { if let key = preferenceSpecification["Type"] as? String, let value = preferenceSpecification["Title"] { defaultsToRegister[key] = value } } userDefaults.register(defaults: defaultsToRegister) } if let groupName = userDefaults.string(forKey: "PSGroupSpecifier") { print("Group name: \(groupName)") } if let _ = userDefaults.string(forKey: "PSTextFieldSpecifier") { if let text = userDefaults.string(forKey: "name_preference") { print("Textfield \(text)") } } if let _ = userDefaults.string(forKey: "PSToggleSwitchSpecifier") { if let value = userDefaults.string(forKey: "enabled_preference1") { print("Toggle \(value)") // 0 or 1 } } if let _ = userDefaults.string(forKey: "PSToggleSwitchSpecifier") { if let value = userDefaults.string(forKey: "enabled_preference2") { print("Toggle2 \(value)") // 0 or 1 } } if let _ = userDefaults.string(forKey: "PSSliderSpecifier") { print("heck....") // No show if let value = userDefaults.string(forKey: "slider_preference") { print("Slider \(value)") } } } }
Posted
by Tomato.
Last updated
.
Post marked as solved
1 Replies
1k Views
How do you save a picture from the capture-screen with AVCaptureSession to Photo? My capture-screen looks like a square as show below. Yet I've ended up with an 1080 × 1920 image as shown below. I have an iPhone XR, and I always end up with 1080 × 1920 images. How come the aspect ration never changes? My code has the following lines import UIKit import AVFoundation class CaptureViewController: UIViewController, AVCapturePhotoCaptureDelegate { var captureSession: AVCaptureSession! var cameraDevices: AVCaptureDevice! var imagePhotoOutput: AVCapturePhotoOutput! enum CameraCase { case front case back } // MARK: - IBAction @IBAction func takePictureTapped(_ sender: UIButton) { snapPicture() } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) prepareCamera(cameraCase: .back) } // MARK: - Camera func prepareCamera(cameraCase: CameraCase) { /* removing existing layers */ if let sublayers = self.view.layer.sublayers { for sublayer in sublayers { if sublayer.isKind(of: AVCaptureVideoPreviewLayer.self) { sublayer.removeFromSuperlayer() } } } /* creating a capture session */ captureSession = AVCaptureSession() guard let device = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: cameraCase == .front ? .front : .back).devices.first else { return } let videoInput = try? AVCaptureDeviceInput(device: device) if captureSession.canAddInput(videoInput!) { captureSession.addInput(videoInput!) imagePhotoOutput = AVCapturePhotoOutput() // setting output destination captureSession.addOutput(imagePhotoOutput) // adding photo output to session } /* creating a capture layer */ let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: captureSession) previewLayer.frame = CGRect(x: 0.0, y: 200.0, width: view.frame.width, height: view.frame.height - 500.0) previewLayer.videoGravity = AVLayerVideoGravity.resize /* adding video capture layer to the view layer */ self.view.layer.addSublayer(previewLayer) /* starting capture session */ DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } } func snapPicture() { let settingsForMonitoring = AVCapturePhotoSettings() imagePhotoOutput?.capturePhoto(with: settingsForMonitoring, delegate: self as AVCapturePhotoCaptureDelegate) } // MARK: - Delegate methods func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { if error == nil { guard let imageData = photo.fileDataRepresentation() else { print("Error while generating image from photo capture data."); return } if let image = UIImage(data: imageData) { saveImage(image) } } } // MARK: - Saving an image to Photo Library func saveImage(_ image: UIImage) { UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError: contextInfo:)), nil) } @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { if let error = error { print("An error has occurred: \(error.localizedDescription)") } else { print("Saved...") } } } Thanks.
Posted
by Tomato.
Last updated
.
Post marked as solved
1 Replies
7.3k Views
I have revisited AVCaptureSession in UIKit to capture a snapshot with the FaceTime camera. And my sample app will crash when AVCaptureSession starts running. Does anyone know how to fix it? The console says the following purple warning. -[AVCaptureSession startRunning] should be called from background thread. Calling it on the main thread can lead to UI unresponsiveness import UIKit import AVFoundation class CaptureViewController: UIViewController, AVCapturePhotoCaptureDelegate { var captureSession: AVCaptureSession! var cameraDevices: AVCaptureDevice! var imagePhotoOutput: AVCapturePhotoOutput! enum CameraCase { case front case back } // MARK: - IBAction @IBAction func selectTapped(_ sender: UIButton) { snapPicture() } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) prepareCamera(cameraCase: .front) } // MARK: - Camera func prepareCamera(cameraCase: CameraCase) { /* removing existing layers */ if let sublayers = self.view.layer.sublayers { for sublayer in sublayers { if sublayer.isKind(of: AVCaptureVideoPreviewLayer.self) { sublayer.removeFromSuperlayer() } } } /* creating a capture session */ captureSession = AVCaptureSession() if cameraCase == .front { guard let device = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices.first else { return } let videoInput = try? AVCaptureDeviceInput(device: device) if captureSession.canAddInput(videoInput!) { captureSession.addInput(videoInput!) imagePhotoOutput = AVCapturePhotoOutput() // setting output destination captureSession.addOutput(imagePhotoOutput) // adding photo output to session } } else { guard let device = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .front).devices.first else { return } let videoInput = try? AVCaptureDeviceInput(device: device) if captureSession.canAddInput(videoInput!) { captureSession.addInput(videoInput!) imagePhotoOutput = AVCapturePhotoOutput() // setting output destination captureSession.addOutput(imagePhotoOutput) // adding photo output to session } } /* creating a capture layer */ let captureVideoLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: captureSession) captureVideoLayer.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) captureVideoLayer.videoGravity = AVLayerVideoGravity.resizeAspect /* adding video capture layer to the view layer */ self.view.layer.addSublayer(captureVideoLayer) /* starting capture session */ captureSession.startRunning() //<<<<<<<<<<<<<<<<<<<<<<<<<<< The console shows a purple warning here. } }
Posted
by Tomato.
Last updated
.
Post marked as solved
1 Replies
701 Views
I have downloaded the UniversalMac_13.0_22A379_Restore.ipsw file. How do we use this file to install the new OS? Thanks.
Posted
by Tomato.
Last updated
.