Hi I want users to be able to Register even if they don't choose a profile picture
Right now I use this code for the profile picture:
let profileImageData = UIImageJPEGRepresentation((userImage.image!), 1)
if (profileImageData != nil) {
let profileImageFile = PFFile (data: profileImageData!)
myUser.setObject(profileImageFile!, forKey: "profile_picture")
}
And each time a user don't choose a profile picture while registering I get this error
fatal error: unexpectedly found nil while unwrapping an Optional value
I want the user to be able to register even if the value is nil.
Thank you very much
I am modifying your code here:
if let profileImageData = UIImageJPEGRepresentation((userImage.image!), 1){
let profileImageFile = PFFile (data: profileImageData!)
myUser.setObject(profileImageFile!, forKey: "profile_picture")
}else{
print("No image selected")
}
Hope this helps!
The problem is that you are trying to force unwrap the userImage.image variable even when its not set. You should force unwrap only when you are sure that the variable has a value.
The below modification should work
if let profileImage = userImage.image{
let profileImageData = UIImageJPEGRepresentation((profileImage), 1)
let profileImageFile = PFFile (data: profileImageData!)
myUser.setObject(profileImageFile!, forKey: "profile_picture")
}else{
//! Handle part when no image is selected
}
Related
I'm using Swift 4 and trying to get images from my server. Using ipconfig in terminal, I know my localhost's ip is 10.43.229.215.
the following code is to retrieve the image data and turn it into UIImage:
func GetImage(url:String) {
let image = String(localIP + url).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: image)
print(image)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print("Client error!")
return
}
guard let data = data else {
print("Error: did not receive data")
return
}
DispatchQueue.main.async {
self.LensImageView.image = UIImage(data: data)
}
}).resume()
}
What I don't understand is that, the image string did show the image I want if I copy/paste the string to my browser
(http://10.43.229.215:3000/lensPic/%E5%A4%AA%E5%A6%83%E7%B3%96%E6%9D%8F.png)
However, error appears at the line self.LensImageView.image = UIImage(data: data) saying Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value.
I'm really confused about:
How can data be nil if there is already a guard let method?
Why can the data be nil is I can show the image through my browser?
Any help is highly appreciated!
The problem lies in making a false assumption about what is nil. It has nothing to do with the image or the data. What’s nil is self.LensImageView, the outlet property.
I am trying to display the image I have stored in Buddy For Parse into a UIImageView, however I keep getting this error:
Could not cast value of type 'PFFileObject' (0x1045e0568) to 'NSString' (0x1041d75d8).
2019-04-13 18:15:09.869460-0500 PerfectLaptop[43839:3094232] Could not cast value of type 'PFFileObject' (0x1045e0568) to 'NSString' (0x1041d75d8).
I have already stored numerous strings into Parse, and am able to access them with no problems, and have stored the image I wanted to use also, however no matter what I try, I can't seem to get it to work. Many of the solutions I have found include casting the object as a PFFile, however this doesn't seem to exist anymore.
let query = PFQuery(className: "whichOneRecommended")
query.findObjectsInBackground { (objects, error) in
if error == nil
{
if let returnedobjects = objects
{
for object in returnedobjects
{
if (object["whichOne"] as! String).contains("\(self.whichOneJoined)")
{
self.laptopImage.image = UIImage(named: (object["laptopImage"]) as! String)
}
}
}
}
}
While the image file is viewable and downloadable in parse, I can't seem to actually have it be displayed in the imageview, and i want the image view to change programmatically by running this function as I have with other parts of the object.
Thanks in advance
The first thing to note is that PFFile has been renamed to PFFileObject.
You are trying to pass object["laptopImage"] which is a value of type Any to UIImage(named:) which can't be done because that function expects a String.
Firstly you need to create a constant of type PFFileObject:
let file = object["laptopImage"] as? PFFileObject
And then download the file data, create a UIImage from the PFFileObject and assign the image to the UIImageView:
file.getDataInBackground { (imageData: Data?, error: Error?) in
if let error = error {
print(error.localizedDescription)
} else if let imageData = imageData {
let image = UIImage(data: imageData)
self.laptopImage.image = image
}
}
Details on this can be found in the section on files in the iOS Guide.
guard let imageString = message,
let imageURL = URL(string: imageString) else { return }
do {
let imageData = try Data(contentsOf: imageURL)
image.image = UIImage(data: imageData)
} catch {
}
I am having issues while updating my iOS app's code to the latest version of Swift.
I have a function:
public class func gifWithURL(gifUrl:String) -> UIImage? {
// Validate URL
guard let bundleURL:NSURL? = NSURL(string: gifUrl)
else {
print("SwiftGif: This image named \"\(gifUrl)\" does not exist")
return nil
}
// Validate data
guard let imageData = NSData(contentsOf: bundleURL! as URL) else {
print("SwiftGif: Cannot turn image named \"\(gifUrl)\" into NSData")
return nil
}
return gifWithData(data: imageData)
}
And am getting a warning on the following line:
guard let bundleURL:NSURL? = NSURL(string: gifUrl)
and am getting the warning:
Explicitly specified type 'NSURL?' adds an additional level of optional to the initializer, making the optional check always succeed
Xcode allows me to fix the problem automatically. When I do this auto-fix, my code changes to:
guard let bundleURL:NSURL NSURL(string: gifUrl)
Which is obviously not the correct syntax.
I am unsure what I need to add/remove to get my code fully up to date with Swift 3 standards and working.
NSURL(string:) will return optional NSURL? instance and you are already optionally wrapping it with guard so remove the : NSURL? because you are setting it again optional instead of non-optional also, in Swift 3 use native URL and Data instead of NSURL and NSData. The whole code would be like.
guard let bundleURL = URL(string: gifUrl), let imageData = try? Data(contentsOf: bundleURL) else {
print("SwiftGif: This image named \"\(gifUrl)\" does not exist")
return nil
}
//Access the imageData here
Note: Data(contentsOf:) will throws exception so you need to catch it using do try catch block.
You are doing it too complicated. In Swift 3, we don't use NSURL. It's just URL:
guard let bundleURL = URL(string: gifUrl) else {
print("SwiftGif: This image named \"\(gifUrl)\" does not exist")
return nil
}
Then you can also get rid of your dangerous force-cast:
guard let imageData = NSData(contentsOf: bundleURL) else {
print("SwiftGif: Cannot turn image named \"\(gifUrl)\" into NSData")
return nil
}
I am not able to figure this one out by my self. I am retrieving some settings stored in Core Data, and print these setting to some UITextFields. This works fine in another VC in the same project but here I get "unexpexpectedly found nil while unwrapping optional value".
I XCode I can see that the values are there? Why do I get this crash?
Please see attached screenshot.
This is the current code I am down to now. Still the same error message in XCode
func getSettingsFromCoreData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DeathMatchSettings")
do{
let results = try context.fetch(request)
let managedObject = results as! [NSManagedObject]
let getDMSettings = managedObject[0]
guard let playerOne = getDMSettings.value(forKey: "playerOne") else {
return
}
print(playerOne)
txtPlayerOne.text = String(describing: playerOne)
}catch{
fatalError("Error in retreiving settings from CoreData")
}
}
Player1 can be nil. You are trying to force downcast it to a value, but it is a fatal error in swift. Use an if let statement to test the value:
if let playerOne = getDMSSettings.value(forKey: "playerOne") as? String {
print(playerOne)
txtPlayerOne.text = playerOne
}
Read more about type casting in docs:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html
You can also use guard statement to unwrap your optional variable. It is better to use forced unwrapping only if you are confident that variable has non-optional value.
do {
guard let playerOne = getDMSettings.value(forKey:"playerOne") else {
return
}
print(playerOne)
txtPlayerOne.text = playerOne
}
So I have been trying to retrieve an image from Parse since yesterday and I am very confused. I read similar questions and examples but all of them were people saving some image first, then retrieving it. What I want to do is simply retrieve an image that I manually uploaded to parse, I have been trying with this:
//Retrieving image from parse
var object = PFObject(className:"ClassImage")
let getParseImg = object["image"] as! PFFile
getParseImg.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if (error == nil){
if let imageData = imageData{
println("Retrieving Image")
let img = UIImage(data:imageData)
self.imageView.image = img
}
}
}
In line two, it throws a "unexpectedly found nil while unwrapping an Optional value", I already tried "if let getParseImg", then it throws another error, in the end the line ended up looking like this:
if let getParseImg = object["image"] as? PFFile{
So after that, everything goes fine and compiles but it doesn't do absolutely anything, it does not get and display the image and it doesn't even print "Retrieving Image", any ideas how can I solve this, I am new to Parse so still getting familiarized with it.
Thanks in advance!
You need to run a query. Also, I used a dictionary called imagesDict in order to ensure your photos are returned in the correct order.
var query = PFQuery(className: "ClassImage")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
let imageObjects = objects as! [PFObject]
for (index, object) in enumerate(imageObjects) {
let thumbnail = object["image"] as! PFFile
thumbnail.getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let image = UIImage(data: imageData!) {
self.imagesDict[index] = image
self.theTableView.reloadData()
}
}
}
}
}
}