Getting Error With Google Maps Places API with lookUpPlaceID - swift3

I'm trying to run the below code :
func mapView(_ mapView: GMSMapView, didTapPOIWithPlaceID placeID: String, name: String, location: CLLocationCoordinate2D) {
print("You tapped \(name): \(placeID), \(location.latitude)/\(location.longitude)")
infoMarker.snippet = placeID
infoMarker.position = location
infoMarker.title = name
infoMarker.opacity = 0;
infoMarker.infoWindowAnchor.y = 1
infoMarker.map = mapView
mapView.selectedMarker = infoMarker
placesClient!.lookUpPlaceID(placeID, callback: { (place: GMSPlace?, error: NSError?) -> Void in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
if let place = place {
print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place placeID \(place.placeID)")
print("Place attributions \(place.attributions)")
} else {
print("No place details for \(placeID)")
}
} as! GMSPlaceResultCallback)
}
As soon as the lookUpPlaceID line runs, it throws the exception :
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Something like this should work for you:
placesClient.lookUpPlaceID(placeId, callback: { (place, error) -> Void in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
if let place = place {
print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place placeID \(place.placeID)")
print("Place attributions \(place.attributions)")
} else {
print("No place details for \(placeID)")
}
})

Related

Type of expression is ambiguous without more context GIDSignIn

I've been following this tutorial to implement Google Sign In: https://www.youtube.com/watch?v=M5LiqOBDeGg
Everything works except one line:
GIDSignIn.sharedInstance.signIn(with: config, presenting: presenting) {user, error in
The error is Type of expression is ambiguous without more context
This is the file:
//
// FirebAuth.swift
// TrippiTest
//
// Created by Dragos Catana on 12.01.2023.
//
import Foundation
import FirebaseAuth
import GoogleSignIn
import Firebase
struct FirebAuth {
static let share = FirebAuth()
private init() {}
func signinWithGoogle(presenting: UIViewController,
completion: #escaping (Error?) -> Void) {
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
// Create Google Sign In configuration object.
let config = GIDConfiguration(clientID: clientID)
// Start the sign in flow!
GIDSignIn.sharedInstance.signIn(with: config, presenting: presenting) {user, error in
if let error = error {
completion(error)
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken
else {
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken,
accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { result, error in
guard error == nil else {
completion(error)
return
}
print("SIGN IN")
UserDefaults.standard.set(true, forKey: "signIn") // When this change to true, it will go to the home screen
}
}
}
}
Just for context, this is the line of code from the Login page
GoogleSiginBtn {
// TODO: - Call the sign method here
FirebAuth.share.signinWithGoogle(presenting: getRootViewController()) { error in
// TODO: Handle ERROR
}
} // GoogleSiginBtn
What should I do?

AVCapturePhotoOutput.capturePhoto produces "unknown error(-11800)" when attempting to capture ipad screen

I'm trying to take a screenshot from a connected iPad using AVCapturePhotoOutput, but when capturePhoto calls my delegate's didFinishingProcessingPhoto method, it gives an unknown error. I think I followed the instructions from the AVFoundation doc on how to capture photos, but none of it seems to describe screen capture, and most of it is focused on iOS. Any ideas how to avoid this error (or even what it might mean?)
Relevant code and output below.
//
// AVCapture.swift
// presenterMode
//
// Created by Ben Jones on 1/8/22.
//
import Foundation
import AVFoundation
import CoreMediaIO
import Combine
class AVDeviceManager : NSObject, ObservableObject {
#Published var avWrappers : [AVWrapper] = []
private var delegates : [DevicePhotoDelegate] = []
private let connectionPublisher = NotificationCenter.default
.publisher(for: NSNotification.Name.AVCaptureDeviceWasConnected)
private var subscriptionHandle : AnyCancellable? = nil
//let disconnectionPublisher = NotificationCenter.default
// .publisher(for: NSNotification.Name.AVCaptureDeviceWasDisconnected)
override init(){
super.init()
//without this ipads won't show up as capture dvices
//From https://stackoverflow.com/questions/48646470/ios-device-not-listed-by-avcapturedevice-devices-unless-quicktime-is-opened
var prop = CMIOObjectPropertyAddress(
mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices),
mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal),
mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMaster))
var allow : UInt32 = 1
let dataSize : UInt32 = 4
let zero : UInt32 = 0
CMIOObjectSetPropertyData(CMIOObjectID(kCMIOObjectSystemObject), &prop, zero, nil, dataSize, &allow)
getCaptureDevices()
subscriptionHandle = connectionPublisher.sink { (message) in
print("got a message from the connection publisher")
let device : AVCaptureDevice = message.object as! AVCaptureDevice;
print(device.deviceType, " localized name: ", device.localizedName, " model id", device.modelID)
var session = AVCaptureSession();
let photoOutput = AVCapturePhotoOutput()
session.beginConfiguration()
guard session.canAddOutput(photoOutput) else { return }
session.sessionPreset = .photo
session.addOutput(photoOutput)
print("output added to session")
do {
try session.addInput(AVCaptureDeviceInput(device: device));
print("input added to session")
session.commitConfiguration();
session.startRunning();
print("session running")
let photoSettings = AVCapturePhotoSettings()
print("about to try to capture a photo with", device.localizedName)
let del = DevicePhotoDelegate(dev: device, man: self)
self.delegates.append(del)
photoOutput.capturePhoto(with: photoSettings, delegate: del)
} catch {
print("couldn't add capture device as input")
}
}
}
func getCaptureDevices() -> Void {
//not relevant for the ipad capture since the ipad doesn't show up in this list at startup
AVCaptureDevice.requestAccess(for: .video) { granted in
if granted {
let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes:
[.externalUnknown, .builtInWideAngleCamera], mediaType: .video, position: .unspecified)
self.avWrappers = discoverySession.devices.map({dev -> AVWrapper in
return AVWrapper(dev: dev, im: GlobalViewModel.staticImage)
})
print(self.avWrappers);
}
}
}
}
struct AVWrapper : Identifiable {
let device: AVCaptureDevice
let imagePreview :CGImage
let id: ObjectIdentifier
init(dev: AVCaptureDevice, im : CGImage){
device = dev
imagePreview = im
id = ObjectIdentifier(device)
}
}
class DevicePhotoDelegate : NSObject, AVCapturePhotoCaptureDelegate {
let device : AVCaptureDevice
let manager : AVDeviceManager
init(dev : AVCaptureDevice, man : AVDeviceManager){
device = dev
manager = man
}
#objc(captureOutput:didFinishProcessingPhoto:error:) func photoOutput(_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photo: AVCapturePhoto,
error: Error?){
print("got the ipad photo!")
if (error != nil) {
print("Error: ", error)
}
manager.avWrappers.append(AVWrapper(dev: device,
im: photo.cgImageRepresentation()!))
}
func photoOutput(_: AVCapturePhotoOutput, willBeginCaptureFor: AVCaptureResolvedPhotoSettings){
print("will begin capture")
}
func photoOutput(_: AVCapturePhotoOutput, willCapturePhotoFor: AVCaptureResolvedPhotoSettings){
print("will capture photo")
}
func photoOutput(_: AVCapturePhotoOutput, didFinishCaptureFor: AVCaptureResolvedPhotoSettings, error: Error?){
print("capture complete")
if (error != nil) {
print("Error: ", error)
}
}
}
Output:
got a message from the connection publisher
AVCaptureDeviceType(_rawValue: AVCaptureDeviceTypeExternalUnknown) localized name: Ben’s iPad model id iOS Device
output added to session
input added to session
2022-01-08 20:26:51.990119-0700 presenterMode[71468:6611851] [] CMIOHardware.cpp:379:CMIOObjectGetPropertyData Error: 2003332927, failed
2022-01-08 20:26:51.990198-0700 presenterMode[71468:6611851] [] CMIO_DALA_Object.cpp:518:GetPropertyData Error: 2003332927, got an error getting the property data mObjectID 39
2022-01-08 20:26:51.994027-0700 presenterMode[71468:6611851] [] CMIOHardware.cpp:420:CMIOObjectSetPropertyData property isn't settable pft glob
2022-01-08 20:26:51.994117-0700 presenterMode[71468:6611851] [] CMIOHardware.cpp:450:CMIOObjectSetPropertyData Error: 1852797029, failed
2022-01-08 20:26:51.995318-0700 presenterMode[71468:6611851] [] CMIOHardware.cpp:379:CMIOObjectGetPropertyData Error: 2003332927, failed
2022-01-08 20:26:51.995525-0700 presenterMode[71468:6611851] [] CMIOHardware.cpp:379:CMIOObjectGetPropertyData Error: 2003332927, failed
2022-01-08 20:26:51.995552-0700 presenterMode[71468:6611851] [] CMIO_DALA_Object.cpp:518:GetPropertyData Error: 2003332927, got an error getting the property data mObjectID 39
session running
about to try to capture a photo with Ben’s iPad
will begin capture
will capture photo
got the ipad photo!
Error: Optional(Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedDescription=The operation could not be completed, NSLocalizedFailureReason=An unknown error occurred (-11800)})
presenterMode/AVCapture.swift:123: Fatal error: Unexpectedly found nil while unwrapping an Optional value
2022-01-08 20:26:55.542549-0700 presenterMode[71468:6611851] presenterMode/AVCapture.swift:123: Fatal error: Unexpectedly found nil while unwrapping an Optional value

SwiftUI Combine function -> any publisher return type

func reqAuth(serviceParams: AuthServiceParams) -> AnyPublisher<AuthResponse, Error> {
var subject = PassthroughSubject<Any,Error>()
AlamofireService.auth(serviceParams: serviceParams).responseObject { (response : DataResponse<AuthResponse>) in
if (response.error != nil ) {
print("❌⭕️❌ Auth login hatalı bir dönüş aldı sorun var.")
subject.send(response.error!)
return
} else {
if let data = response.result.value {
guard let token = data.data?.token else {
print("TOKEN BULUNAMADI")
let authResponse = AuthResponse(
result: "fault",
success: false,
data: nil,
message: "Kullanıcı adı veya şifre hatalı",
errCode: "E0000"
)
subject.send(response)
return
}
print("AuthLogin Token -------> \(token)")
ApplicationVariables.token = token
ApplicationVariables.customer = data.data?.customer
ApplicationVariables.config = data.data?.store?.config
ApplicationVariables.logo = data.data?.store?.logo
subject.send(data)
}else {
let error = NSError(domain: "Bir sorun oluştu. Lütfen yöneticinize başvurunuz.", code: 1001, userInfo: nil)
subject.send(error)
}
}
}
}
This is my code base , the problem is I couldn't find the right return , what should I return in this function or how ? I tried subject.eraseToAnyPublisher() but its not match with return type.
In line with declaring subject var subject = PassthroughSubject<Any,Error>()
change Output generic to AuthResponse
You should send errors as errors rather than values, you can send error with subject.send(completion: .failure(#Error#)).
subject.send(#Output#) sends a value
fixed code:
func reqAuth(serviceParams: AuthServiceParams) -> AnyPublisher<AuthResponse, Error> {
var subject = PassthroughSubject<AuthResponse, Error>()
AlamofireService.auth(serviceParams: serviceParams).responseObject { (response : DataResponse<AuthResponse>) in
guard response.error == nil else {
print("❌⭕️❌ Auth login hatalı bir dönüş aldı sorun var.")
subject.send(completion: .failure(response.error!))
return
}
if let data = response.result.value {
guard let token = data.data?.token else {
print("TOKEN BULUNAMADI")
let authResponse = AuthResponse(
result: "fault",
success: false,
data: nil,
message: "Kullanıcı adı veya şifre hatalı",
errCode: "E0000"
)
subject.send(response)
return
}
print("AuthLogin Token -------> \(token)")
ApplicationVariables.token = token
ApplicationVariables.customer = data.data?.customer
ApplicationVariables.config = data.data?.store?.config
ApplicationVariables.logo = data.data?.store?.logo
subject.send(data)
} else {
let error = NSError(domain: "Bir sorun oluştu. Lütfen yöneticinize başvurunuz.", code: 1001, userInfo: nil)
subject.send(completion: .failure(error))
}
}
}

Cannot fetch multiple CKReference records from public Database in a for loop

I have a contact CKRecord with many location CKRecords ( 1 to many relationship)
Both contact CKRecord and Location CKRecord are created in public Database. I add CKReference fro contact to locaiotn via a field named owningContact on location.
ckRecord["owningContact"] = CKReference(record: contactRecord!, action: .deleteSelf)
I go to cloudKit dashboard and verify both the records exist. The location CKRecord has field owningContact that has the recordName of the contact CKRecord. I defined a function to get locations like this:
private func iCloudFetchLocations(withContactCKRecord: CKRecord, completionHandler: #escaping ([CKRecord]?, Error?) -> Void) {
var records = [CKRecord]()
let recordToMatch = CKReference(recordID: withContactCKRecord.recordID, action: .deleteSelf)
let predicate = NSPredicate(format: "owningContact == %#", recordToMatch)
// Create the query object.
let query = CKQuery(recordType: "location", predicate: predicate)
let queryOp = CKQueryOperation(query: query)
queryOp.resultsLimit = 1
queryOp.qualityOfService = .userInteractive
queryOp.recordFetchedBlock = {
records.append($0)
print($0)
}
queryOp.queryCompletionBlock = { (cursor, error) in
guard error == nil else {
if let ckerror = error as? CKError {
self.aErrorHandler.handleCkError(ckerror: ckerror)
}
return
}
if (cursor != nil) {
let newOperation = CKQueryOperation(cursor: cursor!)
newOperation.resultsLimit = queryOp.resultsLimit
newOperation.recordFetchedBlock = queryOp.recordFetchedBlock
newOperation.queryCompletionBlock = queryOp.queryCompletionBlock
self.publicDB?.add(newOperation)
}
completionHandler(records, error)
}
self.publicDB?.add(queryOp)
}
Then I call the code to fetch location CKRecord based on contact CKRecord like this:
let predicate = NSPredicate(format: "TRUEPREDICATE")
let query = CKQuery(recordType: Cloud.Entity.Contact, predicate: predicate)
publicDB?.perform(query, inZoneWith: nil, completionHandler: { (records, error) in
guard error == nil else {
if let ckerror = error as? CKError {
self.aErrorHandler.handleCkError(ckerror: ckerror)
}
return
completion(false)
}
if let contactRecords = records {
for aContactRecord in contactRecords {
// fetch Location Data
self.iCloudFetchLocations(withContactCKRecord: aContactRecord, completionHandler: { records, error in
guard error == nil else {
if let ckerror = error as? CKError {
self.aErrorHandler.handleCkError(ckerror: ckerror)
}
return
completion(false)
}
if let locationRecords = records {
}
})
}
}
})
I have two contacts the first one has been CKReferenc'ed to the location, where as the second contact is still not yet CKReferenc'ed to the location.
I think here is the problem: First time in the loop contact CKRecord information is sent by calling iCloudFetchLocations which returns immediately without waiting for cloud response, and the for loop sends the second contact and calls iCloudFetchLocations again. Since the second contact has no CKReference to the location, the call fails and I can never get to the first contact's location since it hasn't returned yet.
How to fix this?
I found that I had not set the CKReference field: owningContact as Queryable. The way I found out is printing error like this: 
if let ckerror = error as? CKError {
print(ckerror.userInfo)
print(ckerror.errorUserInfo)
self.aErrorHandler.handleCkError(ckerror: ckerror)
}
As soon as I did that it started working, Since I was in a for loop it was timing out on previous fetch I think.

facebook integration Error 2500 OAuthException xcode 8 Swift 3

I am working on facebook integration in xcode 8 Swift 3.
i have used the following code
let parameters = ["fields": "email, first_name, last_name, picture.type(large)"]
FBSDKGraphRequest.init(graphPath: "me", parameters: parameters).start { (connection, result, error) in
if error != nil{
print(error)
return
}
But I am getting below error.
Optional(Error Domain=com.facebook.sdk.core Code=8 "(null)" UserInfo={com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=An active access token must be used to query information about the current user., com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=2500, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 2500;
"fbtrace_id" = "FmK/8QACfhe";
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}})
can anyone help me out this ??
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
print("Login buttoon clicked")
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name, gender, last_name, email, picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
if ((error) != nil)
{
print("Error: \(error)")
}
else
{
let data:[String:AnyObject] = result as! [String : AnyObject]
print(data["first_name"]!)
print(data["last_name"]!)
print(data["email"]!)
print(data["id"]!)
print(data["gender"]!)
}
})
}