I am using PHAsset in my application where I need to upload image and video to api, for that I need mime type of image and video. In previous version of iOS I was using following code but in iOS 8 I don't know how to get mimetype I have tried looking into apple PHAsset programming guide but unable to find it.
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass
((__bridge CFStringRef)[representation UTI], kUTTagClassMIMEType);
Looking for any guidance.
PHContentEditingInput
has property uniformTypeIdentifier
. You can find more in the documentation.
@import MobileCoreServices.UTType;
...
PHAsset *asset = ...
PHContentEditingInputRequestOptions *options = ...
[asset requestContentEditingInputWithOptions:options completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSString *MIME = (__bridge NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)contentEditingInput.uniformTypeIdentifier, kUTTagClassMIMEType);
}];
Also you can find uniformTypeIdentifier from PHContentEditingInput class. For this; use requestContentEditingInput function from PHAsset
Don't forget to import MobileCoreServices
Sample Swift 3.1 code:
import MobileCoreServices
let options = PHContentEditingInputRequestOptions()
options.isNetworkAccessAllowed = true //for icloud backup assets
let asset : PHAsset = ..... //sampleAsset
asset.requestContentEditingInput(with: options) { (contentEditingInput, info) in
if let uniformTypeIdentifier = contentEditingInput?.uniformTypeIdentifier {
//check type here
if uniformTypeIdentifier == (kUTTypeGIF as String) {
debugPrint("This asset is a GIF👍")
}
}
}
Use the requestImageDataForAsset method of PHImageManager. In it's resultBlock the method returns the UTI-Type for the asset.
I ended up getting the MIME type for a PHAsset as follows (iOS 9+):
@implementation PHAsset (UTI)
- (NSString *)utiMimeType
{
NSString *mimeType = @"image/jpeg";
NSString *uType = [PHAssetResource assetResourcesForAsset:self].firstObject.uniformTypeIdentifier;
if (uType) {
NSString *tagMimeType = (__bridge NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)uType, kUTTagClassMIMEType);
if (tagMimeType)
mimeType = tagMimeType;
}
return mimeType;
}
@end
Couple things to call out/ways to improve:
- I chose to default to image/jpeg if mimeType couldn't be derived.
- It is assuming the first resource is the appropriate one. May not be the case for multi-resource assets (Live Photos, etc).
- I haven't yet tested how/if it works as expected for assets in iCloud that need to be downloaded.
If anyone has insight on #2 or #3, it would be greatly appreciated. I'll update my answer when I find out more.
来源:https://stackoverflow.com/questions/28724615/how-to-get-mime-type-for-image-or-video-in-ios-8-using-phasset