Post

Replies

Boosts

Views

Activity

I want to set label & Imageview in centre of myView but App crashing after adding some constraints
Error:- Thread 1: "Unable to activate constraint with anchors <NSLayoutXAxisAnchor:0x280af8500 \"UILabel:0x103dc4fa0.centerX\"> and <NSLayoutXAxisAnchor:0x280af89c0 \"UIView:0x103dc49d0.centerX\"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal." I've created a function programmatical in Base view controller which returns a view & I've added some constraints to its Function:- func getMarker (lbl:String, img:UIImage) -> UIView { let myView = UIView(frame: CGRect.zero) myView.center = CGPoint(x: 50, y: 160) myView.backgroundColor = UIColor.clear let imageView = UIImageView(image: img) imageView.frame = CGRect(x: 0, y: 0, width: 20, height: 40) myView.addSubview(imageView) let label = UILabel(frame: CGRect(x: 0, y: 45, width: 120, height: 30)) label.text = lbl label.textAlignment = .center label.adjustsFontSizeToFitWidth = true label.textColor = UIColor.black label.backgroundColor = UIColor.white label.layer.borderColor = UIColor.lightGray.cgColor label.layer.borderWidth = 0.5 label.layer.cornerRadius = 5 label.layer.masksToBounds = true label.sizeToFit() NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: myView.centerXAnchor), imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor) ]) myView.addSubview(label) return myView } calling function in another controller but it crashing and showing me the error which I mentioned above Calling function:- getMarker(lbl: device.name ?? "", img: (UIImage(named: icfile) ?? UIImage(named: "truck_1_orange")!))
3
0
1.5k
Mar ’22
Can we show some dynamic text along with the marker on Google maps in Swift?
I'm trying to add some text under marker like in the picture mentioned below,I'm using google maps, Swift I want to add some text under my marker. There is a way to do that? My Code self.mapView.clear(); var bounds = GMSCoordinateBounds(); if let lat = alert?.latitude, let lon = alert?.longitude{ let position = CLLocationCoordinate2D(latitude: lat, longitude: lon) let marker = GMSMarker(position: position); marker.title = alert?.deviceName; marker.groundAnchor = CGPoint(x: 0.5, y: 0.5); marker.map = mapView; bounds = bounds.includingCoordinate(position); } let update = GMSCameraUpdate.fit(bounds) self.mapView.animate(with: update);
0
0
606
Mar ’22
reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'
My app worked fine before adding the check notification allow function. and when i add that function, I got this weird crash that gave an error of 'Modifications to layout engine must not be performed from a background thread after it has been accessed from the main thread'. The code that pops up in debugging is this. Any thoughts? My Code import UIKit import GoogleMaps class HomeViewController: FHBaseViewController { var devices : [Device]? var firstLoad = true; let defaults = UserDefaults.standard; var icons: [String:UIImage] = [:]; @IBOutlet weak var movingView : UIView!; @IBOutlet weak var stoppedView : UIView!; @IBOutlet weak var inYardView : UIView!; @IBOutlet weak var offlineView : UIView!; @IBOutlet weak var statsView : UIView!; @IBOutlet weak var mapBed : UIView!; @IBOutlet weak var mapView : GMSMapView!; @IBOutlet weak var morningLabel : UILabel!; @IBOutlet weak var movingLabel : UILabel!; @IBOutlet weak var stoppedLabel : UILabel!; @IBOutlet weak var inYardLabel : UILabel!; @IBOutlet weak var offlineLabel : UILabel!; @IBOutlet weak var nameLabel : UILabel!; override func viewDidLoad() { super.viewDidLoad(); self.reloadData(); } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); self.tabBarController?.tabBar.isHidden = false; if firstLoad{ firstLoad = false; }else{ if UserService.userInfo != nil{ self.reloadData(); } } } override func connectionResume() { self.reloadData() } func checkNotificationAllowed(){ let data = defaults.object(forKey:"mute") as? Bool print(data!) if (data != nil) == true { let current = UNUserNotificationCenter.current() current.getNotificationSettings(completionHandler: { permission in switch permission.authorizationStatus { case .authorized: print("User granted permission for notification") case .denied: print("User denied notification permission") let alert = UIAlertController(title: "Turn On Notifications".localized(), message: "Notifications are disabled. Please turn on app notifications to get device alerts.".localized(), preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Don't Allow".localized(), style: .cancel, handler: { action in self.dismiss(animated: true, completion: nil) })) alert.addAction(UIAlertAction(title: "Allow".localized(), style: .destructive, handler: { action in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) case .notDetermined: print("Notification permission haven't been asked yet") case .provisional: // @available(iOS 12.0, *) print("The application is authorized to post non-interruptive user notifications.") case .ephemeral: // @available(iOS 14.0, *) print("The application is temporarily authorized to post notifications. Only available to app clips.") @unknown default: print("Unknow Status") } }) } } func showLoginVC(){ UserService.clearUser(); UserService.clearLocalCacheUser(); self.firstLoad = true; if buildType == "GPSTracker" { let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MarocLoginViewController") as! MarocLoginViewController; loginVC.successBlock = { (resp, password) in self.loginSuccess(resp, password: password); } loginVC.modalPresentationStyle = .fullScreen self.present(loginVC, animated: true, completion: {}); } else { let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController; loginVC.successBlock = { (resp, password) in self.loginSuccess(resp, password: password); } loginVC.modalPresentationStyle = .fullScreen self.present(loginVC, animated: true, completion: {}); } } func loginSuccess(_ resp: LoginResponse?, password: String){ if let un = resp?.userName, let name = resp?.name, let apiToken = resp?.apiToken{ let u = User(username: un, name: name, password: password, apiToken: apiToken, isActive: true, baseUrl: Configuration.getBaseUrl()); UserService.setUser(user: u); } self.reloadData(); } func reloadData(){ self.nameLabel.text = UserService.userInfo?.name; self.mapView.clear(); let update = GMSCameraUpdate.zoom(to: 1); self.mapView.moveCamera(update); self.showHud(); DashBoardService.getDashBoard { (resp) in self.hideHud(); if resp?.status == 1{ self.movingLabel.text = "\(resp?.summary?.moving ?? 0)"; self.stoppedLabel.text = "\(resp?.summary?.stopped ?? 0)"; self.inYardLabel.text = "\(resp?.summary?.inyard ?? 0)"; self.offlineLabel.text = "\(resp?.summary?.offline ?? 0)"; DispatchQueue.main.async { self.hideHud(); self.checkNotificationAllowed() } } } DeviceService.getDevice { (resp) in if resp?.status == 1{ self.devices = resp?.devices; self.reloadMap(); } } } }
2
0
837
Mar ’22
Marker change its positon on Zoom in & Zoom out
import UIKit import GoogleMaps class ReportLocationDetailViewController: UIViewController {     var event : ReportDetail?;          @IBOutlet weak var mapView: GMSMapView!;     @IBOutlet weak var zoomInBtn: UIButton!;     @IBOutlet weak var zoomOutBtn: UIButton!;          @IBAction func dismissAction(){         self.dismiss(animated: true) {                      }     }     @IBAction func zoomIn(){         self.mapView.animate(with: GMSCameraUpdate.zoomIn());     }          @IBAction func zoomOut(){         self.mapView.animate(with: GMSCameraUpdate.zoomOut());              }     func setUpUI(){         self.zoomInBtn.layer.cornerRadius = 2.0;         self.zoomInBtn.layer.masksToBounds = true;         self.zoomInBtn.layer.borderColor = UIColor.lightGray.cgColor;         self.zoomInBtn.layer.borderWidth = 1.0;         self.zoomInBtn.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5);                  self.zoomOutBtn.layer.cornerRadius = 2.0;         self.zoomOutBtn.layer.masksToBounds = true;         self.zoomOutBtn.layer.borderColor = UIColor.lightGray.cgColor;         self.zoomOutBtn.layer.borderWidth = 1.0;         self.zoomOutBtn.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5);     }          override func viewDidLayoutSubviews() {         super.viewDidLayoutSubviews();         self.setUpUI();     }          override func viewDidLoad() {         super.viewDidLoad()         UIView.appearance().semanticContentAttribute = .forceLeftToRight     }          override func viewDidAppear(_ animated: Bool) {         super.viewDidAppear(animated);         if let e = self.event, let lat = e.lat, let lon = e.lon{             let position = CLLocationCoordinate2D(latitude: lat, longitude: lon)             let marker = GMSMarker(position: position);             marker.snippet = e.address;             marker.title = e.name;             marker.groundAnchor = CGPoint(x: -6.5, y: -3.0);             marker.map = mapView;             self.mapView.selectedMarker = marker;             let update = GMSCameraUpdate.setTarget(position, zoom: 15)             self.mapView.animate(with: update);         }     } } Map view with correct position MapView After Zoom In MapView After Zoom Out
0
0
772
Mar ’22
Error :- APNS device token not set before retrieving FCM Token for Sender ID '836092823410'. Notifications to this FCM Token will not be delivered over APNS.Be sure to re-retrieve the FCM token once the APNS device token is set.
Am trying to fetch FCM key from firebase but getting fcm key nil & error i mention above Delegate File Google Plist File <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CLIENT_ID</key> <string>836092823410-d76r5bkjrusfmgo6rskqo81l4mk7vmp4.apps.googleusercontent.com</string> <key>REVERSED_CLIENT_ID</key> <string>com.googleusercontent.apps.836092823410-d76r5bkjrusfmgo6rskqo81l4mk7vmp4</string> <key>API_KEY</key> <string>AIzaSyDpP1n_NRqj9c_Mq-pA2PlRez7AnVM5buw</string> <key>GCM_SENDER_ID</key> <string>836092823410</string> <key>PLIST_VERSION</key> <string>1</string> <key>BUNDLE_ID</key> <string>com.iai.tracker</string> <key>PROJECT_ID</key> <string>crucial-audio-334611</string> <key>STORAGE_BUCKET</key> <string>crucial-audio-334611.appspot.com</string> <key>IS_ADS_ENABLED</key> <false/> <key>IS_ANALYTICS_ENABLED</key> <false/> <key>IS_APPINVITE_ENABLED</key> <true/> <key>IS_GCM_ENABLED</key> <true/> <key>IS_SIGNIN_ENABLED</key> <true/> <key>GOOGLE_APP_ID</key> <string>1:836092823410:ios:0312dc35c45b23b9e37feb</string> </dict> </plist>
2
0
18k
Mar ’22
Getting FCM Token nil
** Plist File ** <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CLIENT_ID</key> <string>836092823410-d76r5bkjrusfmgo6rskqo81l4mk7vmp4.apps.googleusercontent.com</string> <key>REVERSED_CLIENT_ID</key> <string>com.googleusercontent.apps.836092823410-d76r5bkjrusfmgo6rskqo81l4mk7vmp4</string> <key>API_KEY</key> <string>AIzaSyDpP1n_NRqj9c_Mq-pA2PlRez7AnVM5buw</string> <key>GCM_SENDER_ID</key> <string>836092823410</string> <key>PLIST_VERSION</key> <string>1</string> <key>BUNDLE_ID</key> <string>com.iai.tracker</string> <key>PROJECT_ID</key> <string>crucial-audio-334611</string> <key>STORAGE_BUCKET</key> <string>crucial-audio-334611.appspot.com</string> <key>IS_ADS_ENABLED</key> <false/> <key>IS_ANALYTICS_ENABLED</key> <false/> <key>IS_APPINVITE_ENABLED</key> <true/> <key>IS_GCM_ENABLED</key> <true/> <key>IS_SIGNIN_ENABLED</key> <true/> <key>GOOGLE_APP_ID</key> <string>1:836092823410:ios:0312dc35c45b23b9e37feb</string> </dict> </plist> Delegate File
0
0
838
Mar ’22
am getting address label nil inUITableViewCell on calling tableviewreload function but after scrolling it appear
I am creating a table that has a prototype cell with an image & 3 labels but is getting an address label nil on calling tableviewreload function but after scrolling, it shows the address My Tableview Code func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {                  var device: Device!         if self.searchOn{             device = searchResult[indexPath.row]         }else{             switch self.stage {             case 0:                 if devices?[indexPath.row].address == "" {                     print("\(devices?[indexPath.row].name ?? "") Address Blank :- \(devices?[indexPath.row].address ?? "")")                 }                 device = devices?[indexPath.row];                 break;             case 1:                 device = movingDevices[indexPath.row];                 break;             case 2:                 device = stoppedDevices[indexPath.row];                 break;             case 3:                 device = offlineDevices[indexPath.row];                 break;             default:                 break;             }         }                  if isDeviceExpired(device){             let cell = tableView.dequeueReusableCell(withIdentifier: "deviceRenewCell", for: indexPath) as! DeviceRenewCell;             cell.device = device             cell.renewBlock = { [weak self] device in                 if let vc = self?.storyboard?.instantiateViewController(withIdentifier: "DeviceRenewalViewController") as? DeviceRenewalViewController{                     vc.preSelectedDevice = device                     self?.navigationController?.pushViewController(vc, animated: true)                 }             }             return cell         }else{             let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! DeviceTableViewCell;             if device.address == "" {                 print("\(device.name ?? "") Address Blank :- \(device.address ?? "")")             }             cell.device = device             return cell         }              } My TableviewCell Code class DeviceTableViewCell: UITableViewCell {     public var device : Device?{         didSet{             self.nameLabel.text = self.device?.name;             self.statusLabel.text = self.device?.status;             let twelevehrsformat = DateUtil.format(self.device?.dtTracker ?? "", fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: "dd-MMM-yy hh:mm:ss a", tf: false)             let twentyfourhrsformat = DateUtil.format(self.device?.dtTracker ?? "", fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: "dd-MMM-yy HH:mm:ss", tf: true)             if UserDefaults.standard.bool(forKey: "hrsFormat") == true {                 self.timeLabel.text = twentyfourhrsformat             } else {                 self.timeLabel.text = twelevehrsformat             }             if self.device?.address == "" {                 print("\(self.device?.name) Address blank :- \(self.device?.address ?? "")")             } else {                 self.addressLabel.text = self.device?.address;             }                          self.speedLabel.text = self.device?.speed;             self.speedUnitLabel.text = self.device?.unitOfSpeed;             if let icon = self.device?.icon{                 self.vehicleImage.yy_setImage(with: URL(string: "\(Configuration.getBaseUrl())\(icon)"), options: [.ignoreFailedURL])             }             if let conn = self.device?.connectionImg{                 self.connectionImage.yy_setImage(with: URL(string: "\(Configuration.getBaseUrl())\(conn)"), options: [.ignoreFailedURL])             }             if let ig = self.device?.ignition{                 if ig == 1{                     self.stateImage.image = UIImage(named: "ignition_on");                 }else{                     self.stateImage.image = UIImage(named: "ignition_off");                 }             }else{                 self.stateImage.image = UIImage(named: "ignition_na");             }         }     }          @IBOutlet weak var nameLabel: UILabel!;     @IBOutlet weak var statusLabel: UILabel!;     @IBOutlet weak var timeLabel: UILabel!;     @IBOutlet weak var addressLabel: UILabel!;     @IBOutlet weak var speedLabel: UILabel!;     @IBOutlet weak var speedUnitLabel: UILabel!;     @IBOutlet weak var vehicleImage: UIImageView!;     @IBOutlet weak var connectionImage: UIImageView!;     @IBOutlet weak var stateImage: UIImageView!;     @IBOutlet weak var bed: UIView!;          override func awakeFromNib() {         super.awakeFromNib()         self.bed.layer.masksToBounds = true;         self.bed.layer.cornerRadius = 3.0;              }          override func setSelected(_ selected: Bool, animated: Bool) {         super.setSelected(selected, animated: animated)                  // Configure the view for the selected state     }      } **Before Scrolling ** **After Scrolling **
2
0
580
Feb ’22
I am Getting error :- 'invalid nib registered for identifier (Alert1TableViewCell) - nib must contain exactly one top level object which must be a UITableViewCell instance'
I am using a custom cell in my tableView but when I run i get the error which I have mentioned in my question. override func viewDidLoad() { super.viewDidLoad()         alertTable.register(UINib(nibName: "Alert1TableViewCell", bundle: nil), forCellReuseIdentifier: "Alert1TableViewCell") } extension AlertViewController: UITableViewDelegate, UITableViewDataSource{     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {         return self.alerts?.count ?? 0;     }     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //        let cell = alertTable.dequeueReusableCell(withIdentifier: "Alert1TableViewCell")! //        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! Alert1TableViewCell;         let cell = tableView.dequeueReusableCell(withIdentifier: "Alert1TableViewCell", for: indexPath) as! Alert1TableViewCell         cell.alert = self.alerts?[indexPath.row];         return cell;     }     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {         tableView.deselectRow(at: indexPath, animated: false);     }     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {         return UITableView.automaticDimension;     }     func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {         return 100;     } } class Alert1TableViewCell: UITableViewCell {          @IBOutlet weak var nameLabel: UILabel!     @IBOutlet weak var descriptionLabel: UILabel!     @IBOutlet weak var timeLabel: UILabel!     @IBOutlet weak var icon: UIImageView!               public var alert : Alert?{         didSet{                          self.nameLabel.text = self.alert?.deviceName;             if self.alert?.alertType?.lowercased() == "ignition on"{                 self.icon.image = UIImage(named: "alert_ignition_on");             }else if self.alert?.alertType?.lowercased() == "ignition off"{                 self.icon.image = UIImage(named: "alert_ignition_off");             }else if self.alert?.alertType?.lowercased() == "overspeed"{                 self.icon.image = UIImage(named: "alert_overspeed");             }else{                 self.icon.image = UIImage(named: "alert_default");             }             let twelevehrsformat = DateUtil.format(self.alert?.dtServer ?? "", fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: "dd-MMM-yyyy hh:mm:ss a", tf: false);             let twentyfourhrsformat = DateUtil.format(self.alert?.dtServer ?? "" , fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: "dd-MMM-yy HH:mm:ss a", tf: true)             if UserDefaults.standard.bool(forKey: "hrsFormat") == true {                 self.timeLabel.text = twentyfourhrsformat             } else {                 self.timeLabel.text = twelevehrsformat             }             self.descriptionLabel.text = self.alert?.address;             print(self.alert?.address ?? "")         }     }     override func awakeFromNib() {         super.awakeFromNib()         // Initialization code     }     override func setSelected(_ selected: Bool, animated: Bool) {         super.setSelected(selected, animated: animated)         // Configure the view for the selected state     }      }
0
0
1.3k
Feb ’22
Am getting wrong index path.row from tableview
__am trying to print my values in table view but am getting double-double index.row value am returning devices.count in numberofrowsinsection function which is 22 but am getting ony 5 rows in cellforrowatindex function __ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {         return self.devices?.count ?? 0;     }          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {         print(devices?.count)         print("INDEXPATH :-----    \(indexPath.row)")         let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath);         if let device = self.devices?[indexPath.row]{             cell.textLabel?.text = device.name; //            print("\(count)   :-   Device :-    \(device)   Index:------\(indexPath.row)")             count += 1         }                  return cell;     }          func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {                  tableView.deselectRow(at: indexPath, animated: false);         if let block = self.deviceDidSelectBlock{             if let devices = self.devices, devices.count > 0 {                 let device = devices[indexPath.row]                 block(device);             }         }         self.dismiss(animated: false) {                      }     }          func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {         return 50;     }          func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {         let loc = touch.location(in: self.view);         if loc.x < self.deviceTable.frame.maxX && loc.x > self.deviceTable.frame.minX && loc.y < self.deviceTable.frame.maxY && loc.y > self.deviceTable.frame.minY{             return false;         }else{             return true;         }     }
2
0
1.6k
Jan ’22
How to pass data from modelView to view in SwiftUI
Am getting my data in AssetList Variable in ModelView File But in View File getting nil ** Model View File ** In this file I have data in AssetList * import SwiftUI class FloatingPanelViewModel: ObservableObject { typealias HomeAPICallback = (Bool,String) -> Void var completion : HomeAPICallback? // var arrayCategoryModel = pListManager.shared.homeOptionsItems var AssetsList = [Asset]() func getAssets(completion: @escaping HomeAPICallback) { self.completion = completion AssetsRequest.shared.getAssetsList(delegate: self) } } extension FloatingPanelViewModel:ServiceRequestDelegate { func successWithdata(response: BaseResponse) { if response.isSuccess { if response.requestType == APIRequests.RType_GetAssets { if let responseData = response.serverData as? [String:AnyObject] { do { AssetsList.removeAll() print(responseData) if let AssetData = responseData["assets"] as? [AnyObject] { let jsonData = try JSONSerialization.data(withJSONObject: AssetData, options: .prettyPrinted) AssetsList = try JSONDecoder().decode([Asset].self, from: jsonData) // for i in AssetsList { // print(i) // } } completion?(true,"") } catch { failureWithdata(response: response) } } } } else { failureWithdata(response: response) } } func failureWithdata(response: BaseResponse) { completion?(false,response.message) } } ** but in view getting nil ** in this file am getting nil after assigning viewModel.AssetsList to Assets * import SwiftUI struct FloatingPanelContent: View { // MARK: - PROPERTIES @ObservedObject var viewModel = FloatingPanelViewModel() @State var Assets: [Asset] = [] init() { viewModel.getAssets { (status, message) in print(status) print(message) } self.Assets = viewModel.AssetsList } // MARK: - BODY var body: some View { ScrollView(.vertical, showsIndicators: false){ VStack(alignment: .center, spacing: 10){ ForEach(viewModel.AssetsList) { asset in // print(asset) AssetsView(asset: asset) .cornerRadius(12) } //: LOOP } } // Scroll View } [Assets Variable print in View File ][1] ScreenShot of Printing AssetsList Variable in ViewModel* ScreenShot of Printing Assets Variable in View *
0
0
653
Nov ’21
Swift UIImagePickerController is not sensitive when clicking the Select button
Upload Image Button @IBAction func uploadImageAction(_ sender: UIButton) {         let picker = UIImagePickerController()         picker.sourceType = .photoLibrary         picker.delegate = self         picker.allowsEditing = true         picker.modalPresentationStyle = .fullScreen         present(picker, animated: true)     } Delegate Functions extension SignUpViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {          func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){                           picker.dismiss(animated: true, completion: nil)         guard let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {             return         }                  guard let imageData = image.pngData() else {             return         }                           storage.child("images/file.png").putData(imageData, metadata: nil) { _, error in             guard error == nil else {                 print("Failed to upload")                 return             }             self.storage.child("images/file.png").downloadURL { url, error in                 guard let url = url, error == nil else{                     return                 }                 let urlString = url.absoluteString                 print("Download URL :- \(urlString)")                              }         }              }          func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {         picker.dismiss(animated: true, completion: nil)                  func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {             // Solve the problem that the cancel button is not sensitive when selecting photos after iOS 11             if (UIDevice.current.systemVersion as NSString).floatValue < 11.0 {                 return             }             if (viewController.isKind(of: NSClassFromString("UIImagePickerController")!)){                 for (index,obj) in viewController.view.subviews.enumerated() {                     if obj.frame.size.width < 42 {                         viewController.view.sendSubviewToBack(obj)                     }                 }             }         }     }      }
1
0
944
Jul ’21
cannot find type 'apirequests' in scope , Cannot find type 'RequestType' in scope and Cannot find 'ServiceStatusCode' in scope Showing error on Xcode 12.4 with M1 Chip
I just started a new project on Xcode 12 with Apple M1 Chip. I did run into issues when I was installing the pods but I was able to fix them using sudo arch -x86_64 gem install ffi then arch -x86_64 pod install. Now, the issue that I am facing is when I added the Alamofire pod for Api Networking. I got an error that said Cannot find type 'apirequests', 'RequestType' in scope and Cannot find type 'ServiceStatusCode' in scope. <------------------------BaseRequest .swift------------------------> BaseRequest.swift <-----------------------------------------------------------------> <------------------------BaseResponse .swift------------------------> BaseResponse.swift <----------------------------------------------------------------------->
6
0
1.3k
Jun ’21
Xcode 12.4 and simulator : black screen on 2018 Mac Mini
I'm runnning Xcode 12.4 &amp; am using Core Data and when I launch a device simulator they only show a black screen. ApDelegate.swift import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? internal func application( application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) - Bool { return true }   func applicationWillTerminate( application: UIApplication) { self.saveContext() } // MARK: UISceneSession Lifecycle func application( application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) - UISceneConfiguration {     return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application( application: UIApplication, didDiscardSceneSessions sceneSessions: SetUISceneSession) { } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "DataModel") container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }()     // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } } ViewController import UIKit import CoreData class TodoListViewController: UITableViewController {      var itemArray = [Item]() let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Items.plist")     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext     override func viewDidLoad() { super.viewDidLoad() //        loadItems() } // MARK: - Tableview Datasource Methods override func tableView( tableView: UITableView, numberOfRowsInSection section: Int) - Int { return itemArray.count } override func tableView( tableView: UITableView, cellForRowAt indexPath: IndexPath) - UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath) let item = itemArray[indexPath.row] cell.textLabel?.text = item.title // Ternary Operater == cell.accessoryType = item.done ? .checkmark : .none return cell } // MARK: - Tableview Delegate Methods override func tableView( tableView: UITableView, didSelectRowAt indexPath: IndexPath) { itemArray[indexPath.row].done = !itemArray[indexPath.row].done saveItems() tableView.reloadData() tableView.deselectRow(at: indexPath, animated: true) } //MARK: - Add New Items     @IBAction func addButtonPressed( sender: UIBarButtonItem) { var textField = UITextField() let alert = UIAlertController(title: "Add New Todoey Item", message: "", preferredStyle: .alert)   let action = UIAlertAction(title: "Add Item", style: .default) { (action) in let newItem = Item(context: self.context) newItem.title = textField.text! newItem.done = false self.itemArray.append(newItem) self.saveItems() self.tableView.reloadData() } alert.addTextField { (alertTextField) in alertTextField.placeholder = "Create new item" textField = alertTextField } alert.addAction(action) present(alert, animated: true, completion: nil) } //MARK: - Model Manupulation Methods func saveItems(){             do {                 try context.save()             } catch {                  print("Error while saving the context \(error)")             }     }           //    func loadItems() { //        if let data = try? Data(contentsOf: dataFilePath!) { //            let decoder = PropertyListDecoder() //            do { //                itemArray = try decoder.decode([Item].self, from: data) //            } catch { //                print("Error decoding Item Array \(error)") //            } //        } // //    } }
0
0
484
Feb ’21