How to check a file is video or image? - ios

I am developing a chat app using parse. I want to play the vodeo when users click on the video message and Display expandable image when the user click on the picture message. for that I need to differentiate image and video. Kindly guide me to do that...

Surely the easiest way will be of course to look at the file extension...?

For future googlers ... on didTapMessageBubbleAtIndexPath delegate you should check for item class
let message = yourMessageArray[indexPath.item]
if message.isMediaMessage() {
if message.media().isKindOfClass(JSQPhotoMediaItem) {
//Handle image
} else if message.media().isKindOfClass(JSQVideoMediaItem) {
let video = message.media() as! JSQVideoMediaItem
let videoURL = video.fileURL
}
}

Save this information in another field on Parse during the asset upload.

Related

How to set crop information for `thumbnailImageData` of CNMutableContact

I create/update contacts, using CNMutableContact.
I can set new image via imageData property, but I need to set custom crop information for creating thumbnail. Property thumbnailImageData is read-only.
Code:
let cnContact = CNMutableContact()
cnContact.imageData = imageData //created before
How to add custom thumbnailImage crop?
It seems that setting a thumbnail is not possible in iOS. However, by definition, a thumbnail of an image is the same image cropped to a smaller dimension. Hence iOS will auto generate the thumbnail from the image data set on the contact while saving the contact.
If you want to setup a different images for thumbnail and actual contact image, iOS will not allow you to do this.
Problem I have:
Before adding a new contact (CNMutableContact reference) in the user's contacts, I want to display the contact to the user. I can use the imageData to setup the new contact's image. However, when using CNContactViewController to display this new contact, the image is not cropped as per thumbnail. The thumbnail image showed looks super weird and scaled. How to resolve this?
Solution:
This occurs because the thumbnailImageData property on the CNMutableContact object is nil. This property cannot be set by the developers. This property can only be set by iOS internals and is auto generated by iOS while saving the contact.
So, before displaying the CNMutableContact object, you should save it to the users contacts, to kick in the auto-thumbnail-generation, and then immediately delete the contact.
The following extension on CNMutableContact depicts what you can do to achieve this.
extension CNMutableContact {
func generateThumbnailImage() {
if self.thumbnailImageData != nil {
return
}
// contact.thumbnailImageData is nil
// First save the contact for the thumbnail to be generated
let saveRequest = CNSaveRequest()
saveRequest.add(self, toContainerWithIdentifier: nil)
do {
try CNContactStore().execute(saveRequest)
} catch let error {
print("Error occurred while saving the request \(error)")
}
// self.thumbnailImageData is not nil. Contact Store will generate the thumbnail for this contact with the imageData provided.
// Now delete the contact
let deleteRequest = CNSaveRequest()
deleteRequest.delete(self)
do {
try CNContactStore().execute(deleteRequest)
} catch let error {
print("Error occurred while deleting the request \(error)")
}
// The contact is removed from the Contact Store
// However, the contact.thumbnailImageData is not nil anymore. Contacts Store has generated the thumbnail automatically with the imageData provided.
}
}

Problems with structs in Swift and making a UIImage from url?

Alright, I am not familiar with structs or the ordeal I am dealing with in Swift, but what I need to do is create an iMessage in my iMessage app extension with a sticker in it, meaning the image part of the iMessage is set to the sticker.
I have pored over Apple's docs and https://www.captechconsulting.com/blogs/ios-10-imessages-sdk-creating-an-imessages-extension but I do not understand how to do this or really how structs work. I read up on structs but that has not helped me accomplishing what Apple does in their sample code (downloadable at Apple)
What Apple does is they first compose a message, which I understood, taking their struct as a property, but I take sticker instead
guard let conversation = activeConversation else { fatalError("Expected a conversation") }
//Create a new message with the same session as any currently selected message.
let message = composeMessage(with: MSSticker, caption: "sup", session: conversation.selectedMessage?.session)
// Add the message to the conversation.
conversation.insert(message) { error in
if let error = error {
print(error)
}
}
They then do this (this is directly from sample code) to compose the message:
fileprivate func composeMessage(with iceCream: IceCream, caption: String, session: MSSession? = nil) -> MSMessage {
var components = URLComponents()
components.queryItems = iceCream.queryItems
let layout = MSMessageTemplateLayout()
layout.image = iceCream.renderSticker(opaque: true)
layout.caption = caption
let message = MSMessage(session: session ?? MSSession())
message.url = components.url!
message.layout = layout
return message
}
}
Basically this line is what Im having the problem with as I need to set my sticker as the image:
layout.image = iceCream.renderSticker(opaque: true)
Apple does a whole complicated function thing that I don't understand in renderSticker to pull the image part out of their stickers, and I have tried their way but I think this is better:
let img = UIImage(contentsOfURL: square.imageFileURL)
layout.image = ing
layout.image needs a UIImage, and I can get the imageFileURL from the sticker, I just cant get this into a UIImage. I get an error it does not match available overloads.
What can I do here? How can I insert the image from my sticker into a message? How can I get an image from its imageFileURL?
I'm not sure what exactly the question is, but I'll try to address as much as I can --
As rmaddy mentioned, if you want to create an image given a file location, simply use the UIImage constructor he specified.
As far as sending just a sticker (which you asked about in the comments on rmaddy's answer), you can insert just a sticker into an iMessage conversation. This functionality is available as part of an MSConversation. Here is a link to the documentation:
https://developer.apple.com/reference/messages/msconversation/1648187-insert
The active conversation can be accessed from your MSMessagesAppViewController.
There is no init(contentsOfURL:) initializer for UIImage. The closest one is init(contentsOfFile:).
To use that one with your file URL you can do:
let img = UIImage(contentsOfFile: square.imageFileURL.path)

How to post a video selected from the library on an apple device to a view controller in xcode using swift

I would like to choose a video from the library(which I have completed) NOW, I want to take that video and display it in a view controller. What do I do? I have looked everywhere and have found nothing.
Here is my code for trying to get the file name of a selected video from the library, which I am trying to display in a webview. It does not work.
videoURL = info[UIImagePickerControllerReferenceURL] as! NSURL?
let fileURL = NSURL(fileURLWithPath: " (videoURL)")
videoView.loadHTMLString( " ", baseURL : nil)
Any help is much appreciated. Thanks!
You'll need to implement the delegate methods.. Check this out:
How to select any Video or Movie file from UIImagePickerController

iMessage extension action when tapped

I have successfully created an iMessage extension where the sender can choose an image, type text on top of the image and then send the new image and text combined to another recipient.
Currently, when the recipient taps the received message, it takes them to the iMessage App Store to download the app.
What I would like is for the recipient to NOT be redirected to the app store, but simply be presented with a larger view of the image they received.
Any help on how to achieve this (if possible) would be appreciated!
Edited:
After more research, I'm wondering if it's possible to send the newly created image (containing the image and text combined) as a MSSticker so when the user taps it, it simply enlarges?
Sending the image as a Message follows the MSMessage format (clicking on the message will direct a user to the app or app store). You can either send the image as a sticker or insert the image into the conversation!
(In case anyone's looking for belated enlightenment).
If you sent the image you create as an Attachment then it appears in the receiver's stream as just an image, without being associated with an app. Only when you send an MSMessage does the signature matching kick in and require the receiver to have the app.
See my im-plausibilities sample for a demo, specifically
func sendAttachment() {
guard let conversation = activeConversation else { fatalError("Expected a conversation") }
guard
let imageData = imageView?.image?.jpegData(compressionQuality: 0.8),
let docUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
else {
dismiss()
return
}
// WARNING this is not great practice - not robust if muliple messages sent without completing upload
attachmentPath = URL(fileURLWithPath: "imPhoto.jpg", relativeTo: docUrl)
if (try? imageData.write(to: attachmentPath!)) != nil {
conversation.insertAttachment(attachmentPath!, withAlternateFilename: "imPhoto.jpg") { (error) in
if let error = error {
os_log("Error with insertAttachment(message)")
print(error)
}
}
}
dismiss()
}

How do i select multiple (2-5) images for an Image picker then return as image view?

Hey so I'm trying to have a button that when pressed allows the user to choose 2-5 pictures from their photo library then have whatever photo chosen be set onto a uiimageview? I was looking online and couldn't find anything related to how to do it in swift?
Thanks
I worked out using this : https://github.com/zhangao0086/DKImagePickerController .
Getting selected image's thumbnail images:
let pickerController = DKImagePickerController()
pickerController.sourceType = .Photo
pickerController.didCancelled = { () in
println("didCancelled")
}
pickerController.didSelectedAssets = { [unowned self] (assets: [DKAsset]) in
println("didSelectedAssets")
println(assets)
for(var i = 0; i<(assets.count); i++){
print(assets[i].url)
self.PickedArray .addObject(assets[i].thumbnailImage!)
}
self.performSegueWithIdentifier("SegueToPhotoLibraryView", sender: self)
Getting selected image's urls :
assets[i].url instead of assets[i].thumbnailImage
Hope it helps!
Currently iOS does not provide an image picker out of the box that lets you pick multiple images from the photo library. UIImagePickerController only lets you select one image.
But there are several image picker implementations available that let you pick multiple images. You can find a whole bunch at cocoacontrols.com as #ytbryan already mentioned.
I am currently not aware of any multiple image picker implemented in Swift. If someone finds one, please edit and post the link.

Resources