facebook integration Error 2500 OAuthException xcode 8 Swift 3 - swift3

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"]!)
}
})
}

Related

How to set userSession in AuthView from SignInWithAppleButton in LoginView in SwiftUI

LoginView
SignInWithAppleButton(
onRequest: { request in
let nonce = randomNonceString()
currentNonce = nonce
request.requestedScopes = [.fullName, .email]
request.nonce = sha256(nonce)
},
onCompletion: { result in
switch result {
case .success(let authResults):
switch authResults.credential {
case let appleIDCredential as ASAuthorizationAppleIDCredential:
guard let nonce = currentNonce else {
fatalError("Invalid state: A login callback was received, but no login request was sent.")
}
guard let appleIDToken = appleIDCredential.identityToken else {
fatalError("Invalid state: A login callback was received, but no login request was sent.")
}
guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
return
}
let credential = OAuthProvider.credential(withProviderID: "apple.com",idToken: idTokenString, rawNonce: nonce)
Auth.auth().signIn(with: credential) { (authResult, error) in
if (error != nil) {
print(error?.localizedDescription as Any)
return
}
guard let user = authResult?.user else {return}
viewModel.userSession = user
I cannot put viewModel.userSession = user either without compile-time error and on some lucky occasions, on app crashing. So the app crashes on apple login and on opening the app, everything works fine.
AuthViewModel
#Published var userSession: FirebaseAuth.User?
#Published var currentUser: User?
Normal Login -->
func login(withEmail email: String, password: String) {
Auth.auth().signIn(withEmail: email, password: password) {result, error in
if let error = error {
self.hapticFeedback.notificationOccurred(.error)
self.errorMessage = "\(error.localizedDescription)"
self.errorOccurred.toggle()
print("DEBUG: Failed to Signin with error \(error.localizedDescription)")
return
}
guard let user = result?.user else { return }
self.userSession = user
self.fetchUser()
self.writeUserData()
}

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

swift 3 http request for json file and inserting into fmdb

I'm having trouble inserting data from the JSON file from my server.
I'm getting the error of
Failed to insert initial data into the database.
Error Domain=FMDatabase Code=1 "near "s": syntax error" UserInfo={NSLocalizedDescription=near "s": syntax error} near "s": syntax error
However, 9 of the data entries are inserted into the database before the error occurs and the app doesn't crash too. I'm wondering if it's a problem with the json file on the server or it's the code that I have. Any suggestions would be much appreciated. I only started 2-3 months ago so perfectionists cut me some slack
func insertMovieData() {
if openDatabase() {
let url = URL(string: "http://blahblahblah")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
var query = ""
let jsonObj = JSON(json)
if jsonObj != JSON.null {
for (_, jsonObj) in jsonObj {
let movieTitle = jsonObj["subject"]
let movieCoverURL = jsonObj["message"]
print(movieTitle)
query += "insert into movies values (null, '\(movieTitle)', '\(movieCoverURL)');"
}
}
if !self.database.executeStatements(query) {
print("Failed to insert initial data into the database.")
print(self.database.lastError(), self.database.lastErrorMessage())
}
else {
print(movies)
}
self.database.close()
}
task.resume()
}
}

Getting 100x100 profile pic using Facebook API, Firebase and Swift

My project had been getting the URL string for the medium sized profile pic using this code:
let downloadMediumPicTask = session.dataTask(with: mediumProfPictureURL) { (data, response, error)
in
// The download has finished.
if let e2 = error {
print("Error downloading profile picture: \(e2)")
} else {
if let res2 = response as? HTTPURLResponse {
print("Downloaded medium profile picture with response code \(res2.statusCode)")
if let imageData2 = data {
mediumProfilePictureUIImageFile = UIImage(data: imageData2)!
print("mediumProfilePictureUIImageFile has now been defined as: \(mediumProfilePictureUIImageFile).")
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadMediumPicTask.resume()
It crashes here giving a 403 response code. The URL that is being referenced is an expired signature URL from Facebook. Firebase doesn't adjust to get the new appropriate URL, and it was from Firebase that I had been getting the URL. I can't figure out how to get it directly as tried below:
func getUrlOfMediumProfilePic(){
if (FBSDKAccessToken.current() != nil) {
let graphPathPart2 = "me/picture"
let paramsPart2 = ["type":"medium", "redirect":"false"]
let completionHandlerPart2 = { (connection: FBSDKGraphRequestConnection?, result: Any?, error: Error?) in
if let error = error {
print("Medium picture graph call contained an error: \(error.localizedDescription)")
return
} else {
guard connection != nil else {
print("getURLOfLargeProfilePic() function aborted bc connection failed.")
return
}
let results = result! as! NSDictionary
let dataDict = results["data"] as! NSDictionary
stringOfMediumProfilePicURLaka100x100 = dataDict["url"] as! String
print("medium picture graph call results define stringOfMediumProfilePicURLaka100x100 as: \(stringOfMediumProfilePicURLaka100x100)")
}
}
let graphRequest = FBSDKGraphRequest(graphPath: graphPathPart2, parameters: paramsPart2)!
graphRequest.start(completionHandler: completionHandlerPart2)
}else{
print("User not logged in when getURLOfMediumProfilePic() function was run.")
return
}
}
This code yields an error with code 8.
Have you tried this:
https://graph.facebook.com/{id}/picture?width=100&height=100
I don't know swift, so I can't help about syntax. I think you can make http request to url and get image.
Hope this help :)

URLRequest gets HTTP error 502 and "connection reset by peer"

Got these errors with this code:
if let url = URL(string: "<valid web service url string>") {
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Basic \(base64Authorization)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
if error == nil {
The same code returns no error with Xcode 7.3 but errors in Xcode 8 after converting to Swift 3.
This happened because of the Swift 3 proposal SE-0054.
base64Authorization was declared this way:
static var base64Authorization:String! {
get {
if base64Auth == nil {
let keyString = "<my key string>"
let plainTextData = keyString.data(using: .utf8, allowLossyConversion: false) as Data!
base64Auth = plainTextData!.base64EncodedString(options: .endLineWithLineFeed) as String!
}
return base64Auth
}
}
base64Authorization returned an Optional which messed up the "Basic \(base64Authorization)" HTTP setting.
This declaration of base64Authorization fixed the problem:
static var base64Authorization:String {
get {
if base64Auth == nil {
let keyString = "<my key string>"
let plainTextData = keyString.data(using: .utf8, allowLossyConversion: false) as Data!
base64Auth = plainTextData!.base64EncodedString(options: .endLineWithLineFeed) as String
}
return base64Auth!
}
}