Use of Undeclared type FBRequest - xcode

When I use the code below for my swift 2 xcode 7 project using parse 1.8.5 sdk, I get the error "use of undeclared type 'FBRequest' " in the first line. I downloaded the last facebook and parse frameworks. Why am I getting this error?
let request:FBRequest = FBRequest.requestForMe()
request.startWithCompletionHandler { (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
if error == nil{
if let dict = result as? Dictionary<String, AnyObject>{
let name:String = dict["name"] as AnyObject? as String
let facebookID:String = dict["id"] as AnyObject? as String
let email:String = dict["email"] as AnyObject? as String
let pictureURL = "https://graph.facebook.com/\(facebookID)/picture?type=large&return_ssl_resources=1"
var URLRequest = NSURL(string: pictureURL)
var URLRequestNeeded = NSURLRequest(URL: URLRequest!)
NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
if error == nil {
var picture = PFFile(data: data)
PFUser.currentUser().setObject(picture, forKey: "profilePicture")
PFUser.currentUser().saveInBackground()
}
else {
println("Error: \(error.localizedDescription)")
}
})
PFUser.currentUser().setValue(name, forKey: "username")
PFUser.currentUser().setValue(email, forKey: "email")
PFUser.currentUser().saveInBackground()
}
}
I am using the frameworks below:
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
import ParseFacebookUtilsV4

There is no FBRequest in Facebook iOS SDK 4.x. Use FBSDKGraphRequest instead. You can read more about migration from Facebook iOS SDK 3.x to 4.x here.

Related

Local Parse Database gives error in SwiftUI

I'm trying to store objects in a local Parse datastore on the device itself. I get an error when retrieving the stored object: 'Method requires Pinning enabled.'
I've implemented 'Parse.enalbelLocalDatastore() in AppDelegate.swift. I tried to hard-code the object to be sure there was an object to retrieve.
let configuration = ParseClientConfiguration
{
$0.applicationId = "..."
$0.clientKey = "..."
$0.server = "..."
}
Parse.enableLocalDatastore()
Parse.initialize(with: configuration)
...
func blancoUser() {
let object = PFObject(className: "UserData")
object["id"] = (UUID().uuidString)
object["LoginName"] = "userName"
object["PinCode"] = "00000"
object["ScreenName"] = "test"
object["YearOfBirth"] = 0
object.pinInBackground()
}
...
let query = PFQuery(className: "UserData")
var users:[UserData] = [UserData]()
query.fromLocalDatastore()
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if let error = error {
print(error.localizedDescription)
} else if let objects = objects
I want to get the variable 'users' with the locally stored user objects. What am I missing? Or does the ParseLocalDatastore work differently in SwiftUI.
Can you try to initialize the SDK like this?
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let parseConfig = ParseClientConfiguration {
$0.isLocalDatastoreEnabled = true
$0.applicationId = parseApplicationId
$0.clientKey = parseClientKey
$0.server = parseServerUrlString
}
Parse.initialize(with: parseConfig)
}
}
Reference: https://docs.parseplatform.org/ios/guide/#local-datastore

Xcode Swift 3 NSURLSession.sharedSession

Im trying to update my basic weather app i made with swift 2 to swift 3 this is my code:
func getWeather(city: String) {
let path = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=095711373620570aa92ee530246dc8af"
let url = NSURL(string: path)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
print(">>>> \(data)")
}
and NSURLSession.sharedSession(5th line) and NSURLResponse(6th line) print out an error
Don't annotate types in the completion handler signature and use the Swift 3 native structures:
func getWeather(city: String) {
let path = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=095711373620570aa92ee530246dc8af"
let url = URL(string: path)
let session = URLSession.shared
let task = session.dataTask(with:url!) { (data, response, error) -> Void in
print(">>>> \(data)")
}
Swift 3 update
URLSession.shared.dataTask()

Need help adding name to qrcode so i can save to parse

I cannot figure out why im getting this error.
This is the function to update a guest(Participant). I'm trying to save the Qr code i created to a PFFile and save to parse.
func update() {
_ = LabelText
let query = PFQuery(className: "Participant")
query.getObjectInBackgroundWithId(LabelText) {
(Update: PFObject?, error: NSError?) -> Void in
Update!["firstname"] = self.firstnameTF!.text
Update!["lastname"] = self.lastnameTF!.text
Update!["grade"] = self.gradeTF!.text
Update!["teacher"] = self.teacherTF.text
Update!["email"] = self.emailTF.text
Update!["phone"] = self.phoneTF.text
Update!["transportation"] = self.transportationTF.text
Update!.saveInBackground()
print("updated")
if self.QrImage == nil {
print("Image is Blank")
return
}else{
//Image is not blank
let imageData = UIImageJPEGRepresentation(self.QrImage!, 1)
let parseImageFile = PFFile(data: imageData!)
Update!.setObject(parseImageFile!, forKey: "qrcode")
Update!.saveInBackgroundWithBlock( {
(success: Bool , error: NSError?) -> Void in
})
}
self.dismissViewControllerAnimated(true, completion: {});
}
}
I can see the image in the self.QrImage field and i only get the error on:
let parseImageFile = PFFile(data: imageData!)
Why am i getting a nil error when it should have a value there?
Edit 1:
let imageData = UIImagePNGRepresentation(self.QrImage!)
let parseImageFile = PFFile(data: imageData!)
Update!.setObject(parseImageFile!, forKey: "qrcode")
Update!.saveInBackgroundWithBlock( {
(success: Bool , error: NSError?) -> Void in
})
}
Same result."fatal error: unexpectedly found nil while unwrapping an Optional value"
Edit 2:
So it seems there must be a name value associated with the image before you upload it to parse. My Image is of a Qrcode i create from other data. here's my code:
func displayQrCode() {
print(self.qrdata.text)
let data = self.qrdata.text!.dataUsingEncoding(NSISOLatin1StringEncoding)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter!.setValue(data, forKey: "inputMessage")
filter!.setValue("Q", forKey: "inputCorrectionLevel")
self.qrcodeImage = filter!.outputImage!
let scaleX = qrCode.frame.size.width / qrcodeImage!.extent.size.width
let scaleY = qrCode.frame.size.height / qrcodeImage!.extent.size.height
let transformedImage = qrcodeImage!.imageByApplyingTransform(CGAffineTransformMakeScale(scaleX, scaleY))
self.qrCode.image = UIImage(CIImage: transformedImage)
print("QRCode Made")
}
now i guess i need to add a name to the self.qrCode.image?
This is what needs to be done before you use UIImagePNGRepresentation:
self.QrImage = UIImage(named: "qrcode.png")

Setting the Desktop background on OSX using Swift 2

After an introduction to Javascript, I'm trying to tackle OSX/iOS programming by creating some simple tools to scratch my own itches.
However, right from the jump I hit a roadblock.
I found two examples that should work.
https://github.com/hinderberg/ios-swift-kurs/blob/master/swift-intro/wallpaper.swift
https://www.snip2code.com/Snippet/196825/Swift-shell-script-to-randomize-wallpape
Here's the second:
#!/usr/bin/env xcrun swift
import Foundation
import AppKit
let imagesDir = "/Users/david/Dropbox/Graphics/Wallpaper-HD/"
var err: NSError?
let fs = NSFileManager.defaultManager()
let filenames = fs.contentsOfDirectoryAtPath(imagesDir, error: &err) as [String]?
if let error = err {
NSLog(error.localizedDescription)
} else {
let imagenames = filenames!.filter { $0.hasSuffix(".jpg") || $0.hasSuffix("png") }
let ir = Int(arc4random_uniform(UInt32(imagenames.count)))
let imgurl = NSURL.fileURLWithPath(imagesDir + imagenames[ir])
let workspace = NSWorkspace.sharedWorkspace()
let screen = NSScreen.mainScreen()
let ok : Bool = workspace.setDesktopImageURL( imgurl!, forScreen: screen!, options: nil, error: nil )
if ok {
println( "New wallpaper: " + imagenames[ir] )
} else {
println("Oops!")
}
}
This didn't work in XCode 7 beta 3.
Hoping to reduce to the essentials, I arrived at:
#!/usr/bin/env xcrun swift
import Foundation
import AppKit
let imagesDir = "/Users/josh/Downloads/"
let singleImage = "/Users/josh/Downloads/xlarge.png"
let imgurl = NSURL.fileURLWithPath(singleImage)
let workspace = NSWorkspace.sharedWorkspace()
let screen = NSScreen.mainScreen()
let ok : Bool = workspace.setDesktopImageURL( imgurl, forScreen: screen!, options: nil, error: nil )
if ok {
print( "New wallpaper set!" )
} else {
print("Oops!")
}
And saved as the file wallpaper.swift.
On execution, the error is:
./wallpaper.swift:17:49: error: extra argument 'error' in call
let ok : Bool = workspace.setDesktopImageURL( imgurl, forScreen: screen!, options: nil, error: nil )
And now I'm completely stuck...
I've tried referring to NSWorkspace and NSScreen documentation as well as running through playground, but it's beyond my current skills.
Removing the extra argument it complains about (error: nil) simply gives a different error:
./wallpaper.swift:13:31: error: cannot invoke 'setDesktopImageURL' with an argument list of type '(NSURL, forScreen: NSScreen?, options: nil)'
let ok : Bool = workspace.setDesktopImageURL( imgurl, forScreen: screen, options: nil )
Where is the code failing, and how can I understand how to make it work properly?
In your example you're passing nil as options to the method.
I guess it worked before but now in the comments you showed the current method signature:
(url: NSURL, forScreen screen: NSScreen, options: [String : AnyObject]) throws
We see that options should be a non-Optional Dictionary.
It means you can't use nil anymore for the options parameter: if you don't have options, just pass an empty Dictionary.
Also, now in Swift 2, this method doesn't return a Bool anymore, it throws.
Meaning you have to use it with do try catch:
do {
let imgurl = NSURL.fileURLWithPath(singleImage)
let workspace = NSWorkspace.sharedWorkspace()
if let screen = NSScreen.mainScreen() {
try workspace.setDesktopImageURL(imgurl, forScreen: screen, options: [:])
}
} catch {
print(error)
}
Updated example for Swift 3:
do {
let imgurl = NSURL.fileURL(withPath: singleImage)
let workspace = NSWorkspace.shared()
if let screen = NSScreen.main() {
try workspace.setDesktopImageURL(imgurl, for: screen, options: [:])
}
} catch {
print(error)
}
For those of us using Xamarin Mac, this can be achieved like so:
string filepath = "/Users/you/Desktop/sweet-wallpaper.jpg";
var workspace = NSWorkspace.SharedWorkspace;
var screen = NSScreen.MainScreen;
NSUrl url = NSUrl.FromFilename(filepath);
NSDictionary options = new NSDictionary();
NSError errorContainer = new NSError();
workspace.SetDesktopImageUrl(url, NSScreen.MainScreen, options, errorContainer);
Updated version for Swift 5.x:
do {
let imageURL = URL(fileURLWithPath: "/path/to/image")
if let screen = NSScreen.main {
try NSWorkspace.shared.setDesktopImageURL(imageURL, for: screen, options: [:])
}
} catch {
print(error)
}

Swift 2 error handling of audio recording code

can someone please assist me? I have some code (which I know runs properly in Xcode 6) that is having difficulty executing in Xcode 7 (due to the changes in error handling for Swift 2). I tried to convert the code using the latest Swift syntax in Xcode 7, but no recommendations were offered. Any suggestions?
//Setup audio session
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord,error: nil)
//Initialize and prepare the recorder
audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error:nil)
audioRecorder.meteringEnabled = true;
audioRecorder.prepareToRecord()
audioRecorder.record()
}
#IBAction func stopAudio(sender: UIButton) {
recordingInProgress.hidden = true
//TODO: Stop recording the user's voice
audioRecorder.stop()
var audioSession = AVAudioSession.sharedInstance();
audioSession.setActive(false, error:nil)
}
The Error messages are for the following code:
session.setCategory(AVAudioSessionCategoryPlayAndRecord,error: nil)
Extra argument 'error' in call
audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error:nil)
Cannot find an initializer for type 'AVAudioRecorder' that accepts an argument list of type '(URL: NSURL?, settings: nil, error: nil)'
audioSession.setActive(false, error:nil)
****Extra argument 'error' in call****
try this class ive tested this and it works in the latest version of swift and Xcode
import UIKit
import AVFoundation
class RecordViewController: UIViewController {
required init(coder aDecoder: NSCoder) {
var baseString : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
var pathComponents = [baseString, NSUUID().UUIDString + ".m4a"]
self.audioURL = NSURL.fileURLWithPathComponents(pathComponents)!
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
var recordSettings: [NSObject : AnyObject] = Dictionary()
recordSettings[AVFormatIDKey] = kAudioFormatMPEG4AAC
recordSettings[AVSampleRateKey] = 44100.0
recordSettings[AVNumberOfChannelsKey] = 2
self.audioRecorder = AVAudioRecorder(URL: self.audioURL, settings: recordSettings, error: nil)
self.audioRecorder.meteringEnabled = true
self.audioRecorder.prepareToRecord()
// Super init is below
super.init(coder: aDecoder)
}
you will then have to implement your buttons of course
something like this
#IBAction func recordPressed(sender: AnyObject) {
if self.audioRecorder.recording {
self.audioRecorder.stop()
self.recordButton.setTitle("RECORD", forState: UIControlState.Normal)
self.playButton.enabled = true
} else {
var session = AVAudioSession.sharedInstance()
session.setActive(true, error: nil)
self.audioRecorder.record()
self.recordButton.setTitle("PLAY", forState: UIControlState.Normal)
self.playButton.enabled = false
}
}
#IBAction func playPressed(sender: AnyObject) {
self.audioPlayer = AVAudioPlayer(contentsOfURL: self.audioURL, error: nil)
audioPlayer.play()
}
}

Resources