Firebase Storage Image download not working properly - ios

I use the following code to download an image from Firebase storage:
storageRef.child(self.fileImageDownloadPath).getData(maxSize: 1 * 1024 * 1024) { (data, error) -> Void in
let userPhoto = UIImage(data: data!)
// ASSIGNS DOWNLOADED PICTURE TO OUTLET
self.sharedProfileImage.image = userPhoto
print("– – – Succesfully downloaded the shared profile picture")
}
The download path is retrieved successfully from the corresponding Firebase database; however, the app always crashes because of the expression let userPhoto = UIImage(data: data!); the console logs a
fatal error: unexpectedly found nil while unwrapping an Optional value
If I try to use simply let userPhoto = UIImage(data: data) a compiler error occurs:
Value of optional type 'Data?' not unwrapped; did you mean to use '!' or '?'?
Do you have any idea how I can solve this? Generally, I am well aware of how to (safely) unwrap optionals – but I can't solve this by myself nonetheless.

The following solved it:
storageRef.child(self.fileImageDownloadPath).getData(maxSize: 10 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
print(error!.localizedDescription)
} else {
self.sharedProfileImage.image = UIImage(data: data!)
print("– – – Succesfully downloaded the shared profile picture")
}
}
With this, I found out that
Object https:/firebasestorage.googleapis.com/v0/b/[...] does not exist
which clearly is because of the missing slash in
https:/firebase[...]

Related

How To Properly Update User Profile Image

What is the updated code to upload user profileImage, I got an error trying to update user profileImage.
How do I fix this error?
Cannot invoke initializer for type 'UIImage' with an argument list of
type '(#escaping () -> ())'
self.ProfileImage.image = UIImage{data; data!}
You are using { braces } whereas you need to use ( round brackets )
myImageView.image = UIImage(data: imageData)
There are few issues with your code such as you are using {} instead of () .
So , the code will actually look like ...
self.ProfileImage.image = UIImage(data: data!)
but since data is optional value , it can come as nil if not handled properly. This will lead to crash within your app . So use optional binding in such cases to check whether the data variables actually contain any values , like the code below.
if let imageData = data{
self.ProfileImage.image = UIImage(data: imageData)
}else{
self.ProfileImage.image = UIImage(named : "image_when_no_value_is_present")
}

Swift Get data from Firebase Storage

I'm trying to fetch image data from firebase storage with swift .
Code :
let ref = Storage.storage().reference().child("users").child("uid").child("savedimage");
let task = ref.getData(maxSize: 1024*1024*12) { (data, error) in
if let data = data , let image = UIImage(data: data) {
print("image exists");
self.imageView.image = image;
}else {
print(error);
}
}
task.resume();
But most of the time the app crash after a second of getting the image , and take me to this :
It's not showing any error in console output so i cannot figure out what's the issue but sometimes it's give me a warning before the crash :
warning: could not execute support code to read Objective-C class data in the process. This may reduce the quality of type information available.
What i'm doing wrong ?

CKRecord fetch return 1 record with empty RecordID

Record from iCloud container is fetched, but there is no RecordID. At the same time in the panel on the site, I see it. I tried to extract the record from another application, I registered the necessary container in the settings - and it was extracted without error.
I do not understand - this is a bug Xcode? After all, the extraction code is identical in the second application, where everything works. And in the debugger at the bottom left you can see that RecordID is not empty.
Code:
privateDatabase.perform(query, inZoneWith: nil) { (results, error) -> Void in
if error != nil {
print(error!.localizedDescription)
result(false)
} else if results != nil, results!.count > 0, let me = results?[0] {
let RN = (me[.recordID] as! CKRecord.ID).recordName
Error:
Thread 2: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Variables View Console:
_recordName __NSCFString * #"UA-kuka-2018-11-16 11:27:59" 0x00000001c0644320
The proper way to get the recordID of a CKRecord is to use the recordID property.
Assuming me is actually a CKRecord:
let RN = me.recordID.recordName

NSInvalidArgumentException when trying to retrieve images

I am getting an error using a "properly working" code in another place:
[Error]: Caught "NSInvalidArgumentException" with reason "*** -[_NSPlaceholderData
initWithContentsOfFile:options:error:]: nil file argument"
I declared an array of arrays group:[[AnyObject]]
In my CellForRowAtIndexPath method in my UITableView I am starting the following query based on an array which is an element of group => group[indexPath.row].
I can get the necessary data without a problem, but when I try to use my getDataInBackgroundWithBlock() method, it throws the error above.
var memberPhotoImages:[UIImage] = [UIImage]()
let buttonImageQuery = PFUser.query()
buttonImageQuery?.whereKey("objectId", containedIn: group[indexPath.row])
buttonImageQuery?.findObjectsInBackgroundWithBlock({ (results, error) -> Void in
if error != nil {
print(error)
} else {
self.memberPhotosFiles.removeAll()
if let results = results {
for result in results {
let buttonPicture = result["firstImage"] as! PFFile
self.memberPhotosFiles.append(buttonPicture)
buttonPicture.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error != nil {
//...
} else {
if let data = imageData {
print("success!")
}}}}}}})
return cell
}
Any ideas how to solve this? tried a lot of typecasting so far, but it must be something else.
edit: It prints "Success!", but also the error msg.
I had to guess from the error, it looks like you're trying to access a file that doesn't exist on the device -[_NSPlaceholderData initWithContentsOfFile:options:error:]: nil file argument The issue could be that you're accessing something from a place where the simulator can get to it (possibly inside the iOS Simulator's files, which are in Application Support,) but the device cannot. Check your code for any hard-coded paths that might lead to a place on your computer rather than accessing the device's filesystem.
It show that your file argument is nil. Most of such cases are due to different file path between simulator and device. Check your code about loading file and compare the path between simulator and device.

Can't load image with UIImage or NSData

I am programming a Swift application, and I can't load image saved in the application by using UIImage(contentsOfFile: imgPath) or NSData(contentsOfFile: imgPath)
private func loadData() {
println("load DATA DANGEROUS")
let (dangerous, err) = SD.executeQuery("SELECT * FROM Dangerous")
if err == nil && !dangerous.isEmpty {
var tabPhoto : [DangerousImage] = []
for d in dangerous {
let desc = d["description"]!.asString()!
let idDangerous = d["id"]!.asInt()!
println("iddangerous : \(idDangerous)")
let (photos, error) = SD.executeQuery("SELECT * FROM Photo WHERE idDangerous = ?", withArgs: [idDangerous])
if error == nil {
for photo in photos {
let imgPath = photo["photoPath"]!.asString()!
println(imgPath)
let uimage = UIImage(contentsOfFile: imgPath) // fatal error: unexpectedly found nil while unwrapping an Optional value
tabPhoto.append(DangerousImage(img: uimage!, path: imgPath))
}
}
println("add ENTRY")
self.tabEntry.append(Entry(descript: desc, tab: tabPhoto))
}
}
println("TAB ENTRY : \(tabEntry)")
}
My picture exists with this path : /var/mobile/Containers/Data/Application/...ID-APP.../Documents/images/JPEG_201506162_101128_IOS_99804574.jpg
Thank for your help.
Ysee
From I can see in your code, you are storing the full path to the image in your database, eg. "/var/mobile/Containers/Data/Application/...ID-APP.../Documents/images/JPEG_201506162_101128_IOS_99804574.jpg". Since iOS8, the folder structure has changed - the UDID in the path is changing every time the app is updated or a new build is installed during development. That's why should store a relative path to your image, eg. "/images/JPEG_201506162_101128_IOS_99804574.jpg" and then get the Documents directory with NSSearchPathForDirectoriesInDomains method.

Resources