How To Properly Update User Profile Image - ios

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

Related

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 ?

Firebase Storage Image download not working properly

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[...]

aws dynamodb how to use object mapper with batch get in ios swift

Thanks in advance for any help. I am trying to get Batch items (Load multiple) items from one DynamoDb table using the AWS iOS SDK (Swift). I can load one item using the Block syntax, but I need to load 10 or more than that. I don't want to use 10 Block calls to load them individually. I tried to follow the attach stackoverflow Link (where the similar solution is given) but I am getting the following compiler error message. I come from Java background, hence could also be a syntax issue. Is it the right way to load multiple items? I don't want to use low level API. Any help, where I am going wrong. Thanks.
aws dynamodb how to use object mapper with batch get in ios
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
var tasksList = Array<AWSTask<AnyObject>>()
for i in 1...10 {
tasksList.append(dynamoDBObjectMapper.load(AWSCards.self, hashKey: "SH_"+String(i), rangeKey: nil))
}
AWSTask.init(forCompletionOfAllTasksWithResults: tasksList).continueWithBlock { (task) -> AnyObject? in
if let cards = task.result as? [AWSCards] {
print(cards.count)
}
else if let error = task.error {
print(error.localizedDescription)
}
return nil
}
Have a try with the following codes (Swift 4.1, Feb 9th, 2018):
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
var tasksList = Array<AWSTask<AnyObject>>()
for i in 1...10 {
tasksList.append(dynamoDBObjectMapper.load(AWSCards.self, hashKey: "SH_"+String(i), rangeKey: nil))
}
AWSTask<AnyObject>.init(forCompletionOfAllTasksWithResults: tasksList).continueWith { (task) -> Any? in
if let cards = task.result as? [AWSCards] {
print(cards.count)
}
else if let error = task.error {
print(error.localizedDescription)
}
return nil
}
Your question is "how to use the object mapper" but it might be more efficient for you to not use it.
However, there is a way to use it. See Niklas's answer here and here (he copy & pasted), but something about it strikes me as fishy. I want to make the assertion that it is not as fast as the built-in batch-get function, but I am unsure. I suspect that this does not complete the items in parallel, or at least not as efficiently as in BatchGetItem.
See the docs: "In order to minimize response latency, BatchGetItem retrieves items in parallel."
According to Yosuke, "Currently, AWSDynamoDBObjectMapper does not support the batch get item. You need to load one item at a time if you want to use the object mapper" as of 2016. This still seems to be the case. I am using a version a couple versions behind, but not too far behind. Someone check.
In conclusion, if you are loading one item at a time, you are likely missing out on the whole purpose of BatchGetItem (low latency).
Pulling from various sources, including John Davis's question here, I have tested and ran this BatchGetItem result. Here ya go.
import AWSDynamoDB
let primaryKeyToSortKeyDict : [String : String] = .... // Your stuff
var keys = [Any]()
for key in primaryKeyToSortKeyDict.keys {
let partitionKeyValue = AWSDynamoDBAttributeValue()
partitionKeyValue?.s = String(key)
let sortValue = AWSDynamoDBAttributeValue()
sortValue?.s = String(primaryKeyToSortKeyDict[key]!)
keys.append(["partitionKeyAttributeName": partitionKeyValue, "sortKeyAttributeName": sortValue])
}
let keysAndAttributesMap = AWSDynamoDBKeysAndAttributes()
keysAndAttributesMap?.keys = keys as? [[String : AWSDynamoDBAttributeValue]]
keysAndAttributesMap?.consistentRead = true
let tableMap = [table : keysAndAttributesMap]
let request = AWSDynamoDBBatchGetItemInput()
request?.requestItems = tableMap as? [String : AWSDynamoDBKeysAndAttributes]
request?.returnConsumedCapacity = AWSDynamoDBReturnConsumedCapacity.total
guard request != nil else {
print("Handle some error")
return
}
AWSDynamoDB.default().batchGetItem(request!) { (output, error) in
print("Here is the batchgetitem output")
if error == nil {
// do output stuff
} else {
// handle error
}
}

Does parse PFUser download all User object columns content?

I have a User class in Parse that contains a profilePicture along with some other User info. I couldn't figure out if when I run a query in Swift and Parse returns the PFUser object, does that object already contain the profilePicture or does it download it when I use
PFUser.currentUser()?["profilePicture"]
The object only contain the profilePicture as a PFFile (PFFile representes a file of binary data stored on the Parse servers). You are simply accessing the PFFile which is by indexing with ["profilePicture"].
To get the actual profilePicture when you use it, you can do something like the following to turn the PFFile into UIImage and display it out.
let imageFile = listingObjectPassed["imageFile"] as! PFFile
imageFile.getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
self.imagePic.image = downloadedImage
}
}

Can't retrieve a picture to swift from parse.com using their documentation

I have been trying to follow parse.com's intruction to retrieve a picture I already successfully uploaded (also using their documentation). My code:
let testObject = PFObject(className: "TestObject")
let file = testObject["SampleImage.png"] as PFFile
file.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
self.mainImg.image = image
print("Image Retreived")
I am getting the error:
"AnyObject! is not convertible to 'PFFile'"
and then it sugests that I include a ! in 'as'. However, when I do, the application runs but does not retrieve anything.
I realize this question is posted elsewhere, but the answer is not working for me. What am I doing wrong?
let testObject = PFObject(className: "TestObject")
This is a new empty object which isn't backed by anything on the server. You need to set the id to a known value and refresh the instance of you need to run a query to find an object before the resulting object will contain anything.

Resources