how to add AuiliaryData(kCGImageAuxiliaryDataTypeHDRGainMap) to a heic image? - heic

I use the 'CGImageDestinationAddAuxiliaryDataInfo' try to add Auxiliary Data, this method can add a AVDepthData as AuxiliaryData to heic image.
But, this method can't help me.
my code is:
func combo(jpgfile:String, hdrGainMap: String, to heicfile:String){
let jpgImage = NSImage(contentsOfFile: jpgfile)
let url = URL(fileURLWithPath: jpgfile)
let cijpg = CIImage(contentsOf: url)
let outputURL: URL? = URL(fileURLWithPath: heicfile)
guard let cgImageDestination = CGImageDestinationCreateWithURL(outputURL! as CFURL, kUTTypeJPEG, 1, nil) else {
return
}
let context = CIContext(options: nil)
let dict: NSDictionary = [
kCGImageDestinationLossyCompressionQuality: 1.0,
kCGImagePropertyIsFloat: kCFBooleanTrue,
]
if let cgImage: CGImage = context.createCGImage(cijpg!, from: cijpg!.extent) {
CGImageDestinationAddImage(cgImageDestination, cgImage, nil)
}
var auxDataType: NSString?
var auxDic = {kCGImageAuxiliaryDataInfoData}
let gainurl = URL(fileURLWithPath: hdrGainMap)
let gainImage = CIImage(contentsOf: gainurl)
let cgGainImage = context.createCGImage(gainImage!, from: gainImage!.extent)
let bytesPerRow = cgGainImage!.bytesPerRow
let width = cgGainImage!.width
let height = cgGainImage!.height
let pixelFormat = cgGainImage?.pixelFormatInfo.rawValue
let gainData = cgGainImage?.dataProvider?.data
let auxDataDic = [kCGImageAuxiliaryDataInfoData:gainData,
kCGImageAuxiliaryDataInfoDataDescription:["BytesPerRow":bytesPerRow, "width":width, "height":height,"Orientation":1,"pixelFormat":pixelFormat]
] as [String : Any]
CGImageDestinationAddAuxiliaryDataInfo(cgImageDestination, kCGImageAuxiliaryDataTypeHDRGainMap, auxDataDic as CFDictionary)
CGImageDestinationFinalize(cgImageDestination)
}
But,the code above will cause a runtime error:
(Fig) signalled err=-17102

Related

ARKit – How to customize (geometry) SCNBox?

I'm using the following code to add a node:
public static func Add (anchor: ARAnchor, node: SCNNode) {
guard let anchor_ = anchor as? ARWorldAnchor else { return }
let initialPos = node.presentation.position
let newNode = SCNNode()
newNode.geometry = SCNBox(width: 2 , height:1, length: 0.5, chamferRadius: 0)//
newNode.geometry?.firstMaterial?.isDoubleSided = true
newNode.geometry?.firstMaterial?.fillMode = SCNFillMode.lines
newNode.geometry?.firstMaterial?.emission.contents = UIColor.green
node.addChildNode(newNode)
}
Result:
My taget:
What do I have to do to achieve the above taget?
** 1 wish you good day!!!**

Core Data migration testing: relationships

I'm trying to test a Core Data migration, but I'm not able to fetch the objects from the database and assert their relationships:
func testV1toV2Migration() async throws {
// read and load the old model
let oldModelURL = Bundle(for: PersistenceController.self).url(forResource: "Remoti.momd/Remoti", withExtension: "mom")!
let oldManagedObjectModel = NSManagedObjectModel(contentsOf: oldModelURL)
XCTAssertNotNil(oldManagedObjectModel)
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: oldManagedObjectModel!)
try! coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
let jobType = createJobType(in: managedObjectContext)
let category = createCategory(in: managedObjectContext)
let location = createLocation(in: managedObjectContext)
let jobList = createJobList(in: managedObjectContext)
let job = createJob(in: managedObjectContext, location, category, jobType, jobList)
try! managedObjectContext.save()
// migrate the store to the new model version
let newModelURL = Bundle(for: PersistenceController.self).url(forResource: "Remoti.momd/Remoti 2", withExtension: "mom")!
let newManagedObjectModel = NSManagedObjectModel(contentsOf: newModelURL)
XCTAssertNotNil(newManagedObjectModel)
let mappingModel = try? NSMappingModel.inferredMappingModel(
forSourceModel: oldManagedObjectModel!,
destinationModel: newManagedObjectModel!
)
let migrationManager = NSMigrationManager(sourceModel: oldManagedObjectModel!, destinationModel: newManagedObjectModel!)
try! migrationManager.migrateStore(
from: self.url,
sourceType: NSSQLiteStoreType,
with: mappingModel,
toDestinationURL: self.newUrl,
destinationType: NSSQLiteStoreType)
let newCoordinator = NSPersistentStoreCoordinator(managedObjectModel: newManagedObjectModel!)
try! newCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.newUrl, options: nil)
let newManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
newManagedObjectContext.persistentStoreCoordinator = newCoordinator
// Testing the migration: Category
let categoryFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Category")
let categories = try! newManagedObjectContext.fetch(categoryFetchRequest) as! [NSManagedObject]
XCTAssertNotNil(categories)
XCTAssertEqual(categories.count, 1)
XCTAssertEqual(categories.first?.value(forKey: "name") as? String, "Software Development")
// Testing the migration: Job
let jobFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Job")
let jobs = try! newManagedObjectContext.fetch(jobFetchRequest) as! [NSManagedObject]
XCTAssertNotNil(jobs)
XCTAssertEqual(jobs.count, 1)
let jobToAssert = try? XCTUnwrap(jobs.first) as? Job
XCTAssertEqual(jobToAssert?.category, categories.first) <-- `XCTAssertEqual failed: ("nil") is not equal to ("Optional(<Category: 0x600002521040> (entity: Category; id: 0x8536c4beaabab28c <x-coredata://E5`
...
How can the relationships be tested?
Thanks in advance!

add/modify/edit the photo's exif in swift

I am building an app which can add/modify/edit the exif after the photo filtered. The photo miss all the exif after adding filter. I have try added the new exif to the photo by attempting using the code below, which is not work. The exif still blank in the Mac App - Photos. How to fix it?
THX
//Code below
imageData = UIImageJPEGRepresentation(outp, 1.0)
let imageSource = CGImageSourceCreateWithData(imageData! as CFData, nil)
let filePath = NSTemporaryDirectory().appending("example.jpg")
let fileURL = URL.init(fileURLWithPath: filePath)
var imageInfo = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil) as! Dictionary<CFString, Any>
var exifDictionay = Dictionary<CFString, Any>()
exifDictionay = imageInfo[kCGImagePropertyExifDictionary] as! Dictionary<CFString, Any>
exifDictionay[kCGImagePropertyExifExposureTime] = "1/3"
exifDictionay[kCGImagePropertyExifISOSpeed] = "200"
exifDictionay[kCGImagePropertyExifFNumber] = "2.4"
exifDictionay[kCGImagePropertyExifApertureValue] = "3.5"
exifDictionay[kCGImagePropertyExifFlash] = "On"
imageInfo[kCGImagePropertyExifDictionary] = exifDictionay
let UTI = CGImageSourceGetType(imageSource!)
let newImageData = NSMutableData()
CGImageDestinationAddImageFromSource(destination!, imageSource!, 0, imageInfo as CFDictionary)
CGImageDestinationFinalize(destination!)
PHPhotoLibrary.shared().performChanges({
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: PHAssetResourceType.photo, data: newImageData as Data, options: nil)
}, completionHandler: nil)

Core Data setting all attributes to nil for first time

I am using Xcode 8 with Swift 3
Core Data setting all the attributes to nil for first time on load with no relationships.
Here is the screenshot.
In Console, i am getting this if App is installed for first time. I have deleted and try to run & install from Xcode number of times. Every time it sets all the values to nil.
"author_id" = nil;
"channel_id" = 0;
"created_at" = nil;
desc = nil;
id = 0;
images = nil;
"is_approved" = 0;
"is_bookmarks" = 0;
"is_like" = 0;
"is_wired" = 0;
"like_count" = 0;
link = nil;
"meta_des" = nil;
"post_id" = 0;
pubDate = nil;
"publisher_id" = 0;
"rss_url" = nil;
"share_cat" = nil;
"share_title" = nil;
"tiny_url" = nil;
title = nil;
"title_tag" = nil;
type = nil;
"updated_at" = nil;
url = nil;
Don't understand whats happening there. Anyone has any idea or hint what am i doing wrong or missing here. And this is only happening for "NewsPost" Entity.
Here is the code where i am adding data to core data.
func addData(entityName: String, entityValues: Any) {
var contextt = NSManagedObjectContext()
if #available(iOS 10.0, *) {
contextt = self.persistentContainer.viewContext
} else {
contextt = self.managedObjectContext
}
/// add data
switch entityName {
case EntityName.NewsEntity:
let singlePost = entityValues as! NSDictionary
let id = singlePost.value(forKey: "id") as! NSNumber
let title = singlePost.value(forKey: "title") as! String
let description = singlePost.value(forKey: "description") as! String
let link = singlePost.value(forKey: "link") as! String
let url = singlePost.value(forKey: "url") as! String
let is_approved = singlePost.value(forKey: "is_approved") as! NSNumber
let meta_des = singlePost.value(forKey: "meta_des") as! String
let title_tag = singlePost.value(forKey: "title_tag") as! String
let share_cat = singlePost.value(forKey: "share_cat") as! String
let author_id = singlePost.value(forKey: "author_id") as! String
let type = singlePost.value(forKey: "type") as! String
let publisher_id = singlePost.value(forKey: "publisher_id") as! NSNumber
let channel_id = singlePost.value(forKey: "channel_id")
let share_title = singlePost.value(forKey: "share_title") as! String
let rss_url = singlePost.value(forKey: "rss_url")
let pubDate = singlePost.value(forKey: "pubDate") as! String
let created_at = singlePost.value(forKey: "created_at") as! String
let updated_at = singlePost.value(forKey: "updated_at") as! String
let like_count = singlePost.value(forKey: "like_count") as! NSNumber
let tiny_url = singlePost.value(forKey: "tiny_url") as! String
let publisher = singlePost.value(forKey: "publisher") as! NSDictionary
let pubName = publisher.value(forKey: "name") as! String
let post = NSEntityDescription.insertNewObject(forEntityName: "NewsPost", into: contextt) as! NewsPost
post.id = Int64(id)
post.title = title
post.desc = description
post.link = link
post.url = url
post.is_approved = Int16(is_approved)
post.meta_des = meta_des
post.title_tag = title_tag
post.share_cat = share_cat
post.author_id = author_id
post.type = type
post.publisher_id = Int64(publisher_id)
post.channel_id = (channel_id as? Int64) ?? 0
post.share_title = share_title
post.rss_url = rss_url as? String ?? ""
post.pubDate = pubDate
post.created_at = created_at
post.updated_at = updated_at
post.like_count = Int64(like_count)
post.tiny_url = tiny_url
let images = singlePost.value(forKey: "images") as! NSArray
do {
let data = try JSONSerialization.data(withJSONObject: images, options: .prettyPrinted)
let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
post.images = string as? String
} catch {
}
print("post data -\(post.managedObjectContext)")
break
case EntityName.Categories:
entity.setValue(entityValues[0], forKey: EntityName.Entities.catName)
break
default:
break
}
/// we save our entity
do {
try contextt.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
This is how i am fetching data from Core Data.
func fetchData(entityToFetch: String, completion: #escaping (_ result: [NSManagedObject]?)->()) {
var context = NSManagedObjectContext()
if #available(iOS 10.0, *) {
context = CoreDataStack().persistentContainer.viewContext
} else {
context = DataController().managedObjectContext
}
// Fetching core data
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityToFetch)
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
print("fetch results- \(results as! [NSManagedObject])")
if results.count > 0 {
completion(results as? [NSManagedObject])
} else {
completion(nil)
}
} catch let error {
completion(nil)
print("fetch error -\(error.localizedDescription)")
}
}
Thank in advance.

Instagram sharing not working on iOS 9

This worked fine on iOS 8, but on iOS 9 the UIDocumentInteractionController does appear with the option Copy to Instagram. Pressing it just dismisses the controller.
Any feedback would be appreciated.
Thanks,
var docController = UIDocumentInteractionController()
let instagramURL = NSURL(string: "instagram://app")
if(UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
var imagePost = cropped
let fullPath = documentsDirectory().stringByAppendingString("insta.igo")
var imageData = UIImagePNGRepresentation(imagePost!)!.writeToFile(fullPath, atomically: true)
let rect = CGRectMake(0, 0, 0, 0)
self.docController.UTI = "com.instagram.exclusivegram"
let igImageHookFile = NSURL(string: "file://\(fullPath)")
self.docController = UIDocumentInteractionController(URL: igImageHookFile!)
self.docController.presentOpenInMenuFromRect(rect, inView: self.view, animated: true)
}
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
return documentsFolderPath
}
The way iOS9 reads it when declaring "insta.igo", now needs to have the "/"
let fullPath = documentsDirectory().stringByAppendingString("/insta.igo")
Complete code
var docController = UIDocumentInteractionController()
let instagramURL = NSURL(string: "instagram://app")
if(UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
var imagePost = cropped
let fullPath = documentsDirectory().stringByAppendingString("/insta.igo")
var imageData = UIImagePNGRepresentation(imagePost!)!.writeToFile(fullPath, atomically: true)
let rect = CGRectMake(0, 0, 0, 0)
self.docController.UTI = "com.instagram.exclusivegram"
let igImageHookFile = NSURL(string: "file://\(fullPath)")
self.docController = UIDocumentInteractionController(URL: igImageHookFile!)
self.docController.presentOpenInMenuFromRect(rect, inView: self.view, animated: true)
}
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
return documentsFolderPath
This solution provided by Andy Shephard worked for me:
https://stackoverflow.com/a/32616355/1500708

Resources