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")
Related
I'm trying to download images from parse via 'Asynchronously'.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell
if(cell == nil) {
cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil) [0] as? CatsTableViewCell
}
if let pfObject = object {
cell?.catNameLabel?.text = pfObject["name"] as? String
var votes:Int? = pfObject["votes"] as? Int
if votes == nil {
votes = 0
}
cell?.catVotesLabel?.text = "\(votes!) votes"
var credit:String? = pfObject["cc_by"] as? String
if credit != nil {
cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
}
cell?.catImageView?.image = nil
if var urlString:String? = pfObject["url"] as? String {
var url:NSURL? = NSURL(string: urlString!)
if var url:NSURL? = NSURL(string: urlString!) {
var error:NSError?
var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)
NSOperationQueue.mainQueue().cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
})
}
}
now I changed few code
completionHandler: {
(response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
cell?.catImageView?.image = UIImage(data: imageData)
to
completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
and no critical errors but the image doesn't show up on the simulator.
Any help would be appreciate. Thank you all.
-first problem-
*And the problem is occurred down below
cell?.catImageView?.image = UIImage(data: imageData)
it says
Value of optional type ‘()?’ not unwrapped; did you mean to use ‘!’ or ‘?’?*
The initializer init(data:) returns an optional UIImage. You should check and unwrap it:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response: NSURLResponse?, imageData: NSData?, error: NSError?) -> Void in
if let e = error {
print(e)
return
}
guard let data = imageData else { return }
if let image = UIImage(data: data) {
cell?.catImageView?.image = image
}
})
Heres a copy of my code where the error is giving me, the error is on the line where it says query.findobjectsInBackgroundWithBlock. The full error message is this: `Cannot convert value type ([AnyObject]!, NSError!) -> Void to expected argument type 'PFQueryArrayResultBlock?'
// Retrieve Messages
func retrieveMessages() {
// Create a new PFQuery
var query:PFQuery = PFQuery(className: "Message")
// Call findobjectsinbackground
query.findObjectsInBackgroundWithBlock {(objects:[AnyObject]!, error:NSError!) -> Void in
// Clear the messagesArray
self.messageArray = [String]()
// Loops through the objects
for messageObject in objects {
// Retrieve the text column value of each PFObject
let messageText:String? = (messageObject as! PFObject)["Text"] as? String
// Assign it into our messagesArray
if messageText != nil {
self.messageArray.append(messageText!)
}
}
// Reload the tableview
self.messageTableView.reloadData()
}
}
The method signature had improved in Swift 2.0 with Parse SDK 1.10.0. Replace [AnyObject]! with [PFObject]?. [PFObject] is an optional because Swift doesn't know if it will exist or not.
func retrieveMessages() {
var query:PFQuery = PFQuery(className: "Message")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
self.messageArray = [String]()
for messageObject in objects {
let messageText:String? = (messageObject as! PFObject)["Text"] as? String
if messageText != nil {
self.messageArray.append(messageText!)
}
}
self.messageTableView.reloadData()
}
}
I have UIImage (got from Parse - convert variable PFFile).
How can I save and load image from this variable?
let a = object["image"] as! PFFile
a.getDataInBackgroundWithBlock({ (data:NSData?, error:NSError?) -> Void in
if (error == nil) {
// I have image, but the next I don't know what I do
let image = UIImage(data:data!)
}
})
Save image png
func saveImage(image:UIImage,name:String){
let selectedImage: UIImage = image
let data:NSData = UIImagePNGRepresentation(selectedImage)
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let success = fileManager.createFileAtPath(path, contents: data, attributes: nil)
print(success)
// Check image saved successfully
let getImagePath = (path as NSString).stringByAppendingPathComponent(name)
if fileManager.fileExistsAtPath(getImagePath) {
// image save success
let image = UIImage(contentsOfFile: getImagePath)!
}
else{
// image save error
}
}
Save other file
static func saveFile(fileData:NSData,name:String)->Bool{
let success = NSFileManager.defaultManager().createFileAtPath(path+"/"+name, contents: fileData, attributes: nil)
return success
}
I am trying to call my image but it is showing this error :
" Cannot assign a value of type UIImage? to a value of type Dynamic " exactly in this line "post.image1 = UIImage(data: data!, scale:1.0)
" .
let postsQuery = Post.query()
postsQuery!.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
self.posts = result as? [Post] ?? []
for post in self.posts {
// 2
let data = post.imageFile?.getData()
// 3
post.image1 = UIImage(data: data!, scale:1.0)
}
// 9
self.tableView.reloadData()
}
}
You have to unwrap like as :
if let image = UIImage(data:yourImageData) {
DispatchQueue.main.async {
self.yourImageView.image = image
}
}
I'm new to swift. I am trying to create a call to Google's API to convert any inputted addresses to a long, lat location on google maps, using their sdk.
I thought it'd be easier to start by following a tutorial http://www.appcoda.com/google-maps-api-tutorial/, then dissecting it. But I cannot seem to get it this particular line working. It will come out with a "error-exc-bad-instruction-code-exc-i386-invop-subcode-0x0" on the dicitonary line. I read other sample work on reverse geocoding that are to date, and they look very similar, but none are working. What am I doing wrong?
let dictionary: Dictionary<NSObject, AnyObject> =
NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options:
NSJSONReadingOptions.MutableContainers, error: &error) as!
Dictionary<NSObject, AnyObject>
Full function below:
func geocodeAddress(address: String!, withCompletionHandler completionHandler: ((status: String, success: Bool) -> Void)) {
if let lookupAddress = address {
var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
geocodeURLString = geocodeURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let geocodeURL = NSURL(string: geocodeURLString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let geocodingResultsData = NSData(contentsOfURL: geocodeURL!)
var error: NSError?
let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! Dictionary<NSObject, AnyObject>
// let dictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! Dictionary
if (error != nil) {
println(error)
completionHandler(status: "", success: false)
}
else {
// Get the response status.
let status = dictionary["status"] as! String
if status == "OK" {
let allResults = dictionary["results"] as! Array<Dictionary<NSObject, AnyObject>>
self.lookupAddressResults = allResults[0]
// Keep the most important values.
self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as! String
let geometry = self.lookupAddressResults["geometry"] as! Dictionary<NSObject, AnyObject>
self.fetchedAddressLongitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lng"] as! NSNumber).doubleValue
self.fetchedAddressLatitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lat"] as! NSNumber).doubleValue
completionHandler(status: status, success: true)
}
else {
completionHandler(status: status, success: false)
}
}
})
}
else {
completionHandler(status: "No valid address.", success: false)
}
}
For Swift 2, this can be used:
First, declare your variable as an empty dictionary outside of the do-catch block and do the assignment in the block, like below
do {
dictionary = try NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<NSObject, AnyObject>
} catch {
//something
}