Uploading multiple Images to Parse - swift

I am wondering if its possible to upload 10 images to parse, and then be able to display them in TableView displaying the users username.
So basically when I download them from parse I'm guessing there needs to be something linking those images to the same user or that 1 individual post...
Not sure if this is possible, but I read these two questions and I think you can!
How do I store multiple pictures to a single column in Parse?
Storing images from [UIImage] array to Parse
If anyone understands what I mean, I would love your help!
Best regards.

As discussed, you can add the array of images to a column in your User class, the code below allows you to create a new user and will take an image array and create as many columns as necessary. They will be titled "imageArray0", "imageArray1" and so on. The next time you create a user with images they will automatically be added to the corresponding columns in Parse.
UPDATE
Added image conversion:
let user = PFUser()
user.username = chosenUsername
for i in imageArray.indices {
let imageData = imageArray[i].mediumQualityJPEGNSData
let imageFile = PFFile(name: "image.JPEG", data: imageData)
user["imageArray\(i)"] = imageFile
}
user.signUpInBackgroundWithBlock({
success, error in
if error == nil {
} else {
}
})
I also use this extension to easily convert images to various qualities:
extension UIImage {
var uncompressedPNGData: NSData { return UIImagePNGRepresentation(self)! }
var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)! }
var highQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.75)! }
var mediumQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.5)! }
var lowQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.25)! }
var lowestQualityJPEGNSData:NSData { return
UIImageJPEGRepresentation(self, 0.0)! }
}

I'm not sure that is possible but is unnecessary for two reasons:
Speed of query when you want to retrieve the images array
You can save each image under the same row but separately under the Image x number
and finally you can't save a UIImage Array it will have to be a NSData Array so convert the UIImages into NSData's using
let image1 : NSData = UIImagePNGRepresentation([UIImage][0]!)!
let image2 : NSData = UIImagePNGRepresentation([UIImage][1]!)!
let image3 : NSData = UIImagePNGRepresentation([UIImage][2]!)!
let imageArray : [NSData] = [image1, image2, image3]

Related

fetch last item in binary data set for display

My swifts code goal is to fetch the last image from binary data pic and display it in imageview picture. Right now its cusing a runtime error with indexpath. I did a similar thing with a string and it worked. The problem is converting binary data to a uiimage.
var picture = UIImageView()
var itemName : [NSManagedObject] = []
var itemNamez : [Info] = []
func loadImage(){
if let imageData = itemNamez[IndexPath.last] {
let coredataLoadedimage = UIImage(data: imageData)
picture.image = coredataLoadedimage
}
}

Swift: Saving Multiple Images to Core Data

I have a Recipe entity with a one-to-many relationship to RecipeImage. The problem I'm having is how to properly save multiple images. What I'm trying to do is once I selected the images, I store them in a tempImageArray. Once I select "Done" I try to convert images within tempImageArray into an array of data since Core Data only accept images as Binary Data. I then set my recipe.images as that array of data.
Currently, I'm only able to save 1 photo instead multiple.
I think im close to the solution but just needs some guidance. Any help you be much appreciated!
class ListDetailViewController: UITableViewController {
var recipeToEdit: Recipe?
var recipeImages = [RecipeImage]()
//image collection
var tempImageArray = [UIImage]()
private func createRecipe() {
let context = CoreDataManager.shared.persistentContainer.viewContext
let recipe = NSEntityDescription.insertNewObject(forEntityName: "Recipe", into: context) as! Recipe
recipe.setValue(textField.text, forKey: "name")
let image = NSEntityDescription.insertNewObject(forEntityName: "RecipeImage", into: context) as! RecipeImage
for i in tempImageArray {
image.imageData = i.jpegData(compressionQuality: 0.8)
recipeImages.append(image)
}
recipe.images?.setValue(recipeImages, forKey: "images")
image.recipe = recipe
do {
try context.save()
//Perform save
navigationController?.popViewController(animated: true)
self.delegate?.didAddRecipe(recipe: recipe)
} catch let saveErr {
print("Failed to save recipe", saveErr)
}
}

Is there a way to control the sort order when you create a new album to save images onto photo library?

Summary:
Is there a way to control the sort order for an album created by an app on a users device? I would like an album I created to sort by date, but it sorts by download order.
Details:
I am using the function save() below to save a UIImage to an album on a user's iPhone. It works great but the image loses its original create time when the copy is saved. To address this I read the create time when I upload an image to the server. That way I just assign it to the image when the asset is created with assetChangeRequest.creationDate = storedImageDate
PHPhotoLibrary.shared().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection)
assetChangeRequest.creationDate = storedImageDate
let assetEnumeration:NSArray = [assetPlaceholder!]
albumChangeRequest!.addAssets(assetEnumeration)
}, completionHandler: { success, error in
if error != nil {
print("\(error?.localizedDescription ?? "")")
}
})
The above works great and when I look at the newly created image it is in the created album, the images have the correct date on the image, and the images viewed in camera roll are sorted by the image create date as expected. The issue arises when go to the album my app created for images. There the images have the image date, but they are sorted by the order they downloaded not the image. I also noticed that when I long press images in the album it lets me move the order around.
Did I do something wrong creating my album? Can I set it to sort by image date? Perhaps there is a way to change the sort order for my album? Is there a way to fetch loop through the album to order it by date?
This is the full function where an image is saved into a created album which does not sort by the image creation date.
func save(image:UIImage, albumName:String) {
var albumFound = false
var assetCollection: PHAssetCollection!
var assetCollectionPlaceholder: PHObjectPlaceholder!
// https://stackoverflow.com/questions/27008641/save-images-with-phimagemanager-to-custom-album
// Check if the Album exists and get collection
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %#", albumName)
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _: AnyObject = collection.firstObject {
albumFound = true
assetCollection = collection.firstObject
} else {
//If not found - Then create a new album
PHPhotoLibrary.shared().performChanges({
let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
albumFound = success
if (success) {
let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [assetCollectionPlaceholder.localIdentifier], options: nil)
print(collectionFetchResult)
assetCollection = collectionFetchResult.firstObject
}
})
}
if albumFound {
PHPhotoLibrary.shared().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection)
assetChangeRequest.creationDate = storedImageDate
let assetEnumeration:NSArray = [assetPlaceholder!]
albumChangeRequest!.addAssets(assetEnumeration)
}, completionHandler: { success, error in
if error != nil {
print("\(error?.localizedDescription ?? "")")
}
})
}
}
Instead of using addAssets like you did in performChanges 'albumChangeRequest!.addAssets(assetEnumeration)'.
You should use insertAssets at indexes which controls the position the images are added to the album, much like NSArray insertObject atIndex method.
Swift
func insertAssets(_ assets: NSFastEnumeration,
at indexes: IndexSet)
Objective-C
- (void)insertAssets:(id<NSFastEnumeration>)assets
atIndexes:(NSIndexSet *)indexes;
https://developer.apple.com/documentation/photokit/phassetcollectionchangerequest/1619447-insertassets

Swift Image Name Compare

I am using the below code to work out if the image name in box1Image is equal to "sallywin.png".
Id doesnt seem to work.
How would I go about coding this?
Any help much appreciated
if (box1Image.image?.isEqual(UIImage(named: "smswin.png")))! {
self.box1Image.image = UIImage(named:"sallywin.png")
}
You cannot directly compare two images are same. You can get the images as NSDATA and then you can compare two NSDATA values are equal.
You can compare 2 images using NSData.
let imageName1 : UIImage = UIImage(named: "Selected_1.png")!
let imageName2 : UIImage = UIImage(named: "UnSelected.png")!
let imageView = UIImageView(image: imageName1)
if imageCompare(imageView.image!, isEqualTo: imageName2)
{
print("TRUE")
}
else
{
print("FALSE")
}
func imageCompare(image1: UIImage, isEqualTo image2: UIImage) -> Bool {
let data1: NSData = UIImagePNGRepresentation(image1)!
let data2: NSData = UIImagePNGRepresentation(image2)!
return data1.isEqual(data2)
}

Swift core data FetchRequest NSData to UIIMage

Good morning all, I am using Swift "new for me" and core data I am trying to fetch my stored UIIMage from core data the following way. FYI it is saved as Binary Data in core. And I can see the data if I NSLog it. My Fetch Request looks like this. I have NO ERRORS but my image is not showing.
When I save to Core Data the NSLog looks like this..
Did I get to Save Image
2015-10-12 09:05:43.307 Car-Doc-Safe-Plus[13972:3524049] The NewImage has this in it (entity: Documents; id: 0x7fd4c0432060 ; data: {
autoClub = nil;
driverLicense = <89504e47 0d0a1a0a 0000000d 49484452 00000215 00000155 08020000 00d7368a d8000000 01735247 4200aece 1ce90000 001c>;
insuranceID = nil;
noteText = nil;
plate = nil;
registration = nil;
})
But when i Fetch it looks like this..
The Request has this in it (entity: Documents; predicate: ((null)); sortDescriptors: ((null)); type: NSManagedObjectResultType; )
**override func viewDidLoad() {
super.viewDidLoad()
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
let request = NSFetchRequest(entityName: "Documents")
request.returnsObjectsAsFaults = false;
let results : NSArray
try! results = context.executeFetchRequest(request)
if results.count > 0 {
let res = results[0] as! NSManagedObject
carImageView.image = res.valueForKey("driverLicense")as? UIImage
}
}**
I know I am missing something but I cannot figure it out. Any help is greatly appreciated.
JZ
The "binary data" type in Core Data is intended for reading and writing NSData objects. Since you want to read/write UIImage, you need to use the "transformable" type. With transformable, Core Data will attempt to use NSCoding to encode/decode the data, converting it to/from NSData as needed (Swift as? will not do this). Since UIImage conforms to NSCoding, you don't need to do any extra work except to tell Core Data to convert the data.