How to get CGPDFDictionaryRef keys - ios

I would like to get all the keys of an CGPDFDictionaryRef. so far this what I found from stackoverflow
Here is my code in swift:
func printPDFKeys(key: UnsafePointer<Int8>, ob: CGPDFObjectRef, info: UnsafeMutablePointer<()>) -> Void{
NSLog("key = %s", key);
//return (key, ob , info)
}
This function is then called like this.
let myDoc = CGPDFDocumentCreateWithURL(url)
if myDoc != nil {
let myCatalog=CGPDFDocumentGetCatalog(myDoc)
CGPDFDictionaryApplyFunction(myCatalog, printPDFKeys, nil);//Compiler error here
}
However I am getting an error that
a c function pointer can only be formed from a reference to a 'func'
or a literal closure
I have also tried using a Closure like this:
var printPDFKeys: ( UnsafePointer<Int8>, CGPDFObjectRef, UnsafeMutablePointer<()> )-> Void
printPDFKeys={
key,ob,info in
NSLog("key = %s", key);
}
I am still getting the same error. How could I go about it

the correct closure syntax would be:
CGPDFDictionaryApplyFunction(myCatalog, { (key, object, info) -> Void in
// do something
}, nil)

Related

CMVideoFormatDescriptionCreateFromH264ParameterSets throw Initialization of 'UnsafePointer<Int>' results in a dangling pointer

So previously I opened Initialization of 'UnsafePointer<Int>' results in a dangling pointer but the mods said it's a duplicate one.
However I don't think this is a duplicate one, as the links being referred in that post cannot easily direct to a solution. Thus I have to open a new one after 3 days. I tried what is answered from #bscothern in the previous post, but more errors come.
The code being used currently is like below from #bscothern, and it still throws
Generic parameter 'R' could not be inferred
var formatDesc: CMVideoFormatDescription?
func createH264FormatDescription(SPS: Array<UInt8>, PPS: Array<UInt8>) -> OSStatus {
if formatDesc != nil { formatDesc = nil }
let status = SPS.withUnsafeBufferPointer { SPS in
PPS.withUnsafeBufferPointer { PPS in
let paramSet = [SPS.baseAddress!, PPS.baseAddress!]
let paramSizes = [SPS.count, PPS.count]
return paramSet.withUnsafeBufferPointer { paramSet in
paramSizes.withUnsafeBufferPointer { paramSizes in
CMVideoFormatDescriptionCreateFromH264ParameterSets(allocator: kCFAllocatorDefault, parameterSetCount: 2, parameterSetPointers: paramSet.baseAddress!, parameterSetSizes: paramSizes.baseAddress!, nalUnitHeaderLength: 4, formatDescriptionOut: &formatDesc)
}
}
}
}
return status
}
Original question from previous post:
So I have some code to create H264ParameterSets like:
var formatDesc: CMVideoFormatDescription?
func createH264FormatDescription(SPS: Array<UInt8>, PPS: Array<UInt8>) -> OSStatus {
if formatDesc != nil { formatDesc = nil }
let paramSet = [UnsafePointer<UInt8>(SPS), UnsafePointer<UInt8>(PPS)]
let paramPointers = UnsafePointer<UnsafePointer<UInt8>>(paramSet)
let paramSizes = UnsafePointer<Int>([SPS.count, PPS.count])
let status = CMVideoFormatDescriptionCreateFromH264ParameterSets(allocator: kCFAllocatorDefault, parameterSetCount: 2, parameterSetPointers: paramPointers, parameterSetSizes: paramSizes, nalUnitHeaderLength: 4, formatDescriptionOut: &formatDesc)
return status
}
Starting on Xcode 11.4 I got warnings for those UnsafePointer(), which seems not happen before:
Initialization of UnsafePointer<UInt8> results in a dangling pointer
Initialization of UnsafePointer<UnsafePointer<UInt8>> results in a dangling pointer
Initialization of UnsafePointer<Int> results in a dangling pointer
I'm not sure why we see this? and how can I remove the warning? Thank in advance.
When you find some error message like: Generic parameter 'R' could not be inferred, there may be two possible reasons.
There is some type-related error somewhere, so Swift cannot infer the actual type R in that context
The expression is a little more complex than Swift can infer the type
In case 1, you need to find where is the actual error causing the issue.
In case 2, you can add some explicit type annotations to help Swift infer the types.
Please try something like this:
var formatDesc: CMVideoFormatDescription?
func createH264FormatDescription(SPS sps: Array<UInt8>, PPS pps: Array<UInt8>) -> OSStatus {
if formatDesc != nil { formatDesc = nil }
let status = sps.withUnsafeBufferPointer { spsBP->OSStatus in //<- Specify return type explicitly.
pps.withUnsafeBufferPointer { ppsBP in
let paramSet = [spsBP.baseAddress!, ppsBP.baseAddress!]
let paramSizes = [spsBP.count, ppsBP.count]
return paramSet.withUnsafeBufferPointer { paramSetBP in
paramSizes.withUnsafeBufferPointer { paramSizesBP in
CMVideoFormatDescriptionCreateFromH264ParameterSets(allocator: kCFAllocatorDefault, parameterSetCount: 2, parameterSetPointers: paramSetBP.baseAddress!, parameterSetSizes: paramSizesBP.baseAddress!, nalUnitHeaderLength: 4, formatDescriptionOut: &formatDesc)
}
}
}
}
return status
}

Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' error

I have this script use to check whether the *downloaded file from iCloud is available or not. But unfortunately I encountered error Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' in some lines of code. Please help me to solve this issue because it is my first time to create a code to check whether the downloaded file is available in the icloud or not.
Please refer to the image below as sample of the error and also codes are available below for your reference. Hope you could help me. Thank you.
Sample screenshot of error
//-------------------------------------------------------------------
// ダウンロードできるか判定 Judgment or can be downloaded
//-------------------------------------------------------------------
func downloadFileIfNotAvailable(_ file: URL?) -> Bool {
var isIniCloud: NSNumber? = nil
do {
try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey)
if try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey) != nil {
if isIniCloud?.boolValue ?? false {
var isDownloaded: NSNumber? = nil
if try (file as NSURL?)?.getResourceValue(&isDownloaded, forKey: .ubiquitousItemIsDownloadedKey) != nil {
if isDownloaded?.boolValue ?? false {
return true
}
performSelector(inBackground: #selector(startDownLoad(_:)), with: file)
return false
}
}
}
} catch {
}
return true
}
It looks like you copied and pasted some really old code. Besides, this is Swift, not Objective-C. Do not use NSURL or getResourceValue. Your code should look more like this:
if let rv = try file?.resourceValues(forKeys: [.isUbiquitousItemKey]) {
if let isInCloud = rv.isUbiquitousItem {
// and so on
}
}
And so on; the same pattern applied to other keys. Note that there is no .ubiquitousItemIsDownloadKey either. You can condense things like this:
if let rv = try file?.resourceValues(
forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey]) {
if let isInCloud = rv.isUbiquitousItem {
if let status = rv.ubiquitousItemDownloadingStatus {
if status == .downloaded {
}
}
}
}

How to receive String Array from Parse Cloud Code in Swift?

I've written a Parse cloud code function which returns some data from the database. I see those in the "response" when I do a println in XCode. It looks like it's wrapped in a double optional!?
What I'm making wrong in the if let and in the for loop? How do I get (unwrap) a String Array out of it?
My code in Swift:
PFCloud.callFunctionInBackground("TopTwo", withParameters: ["rating":5]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(response!.count) scores.")
println("Here are the flower names: \(response)")
if let objects = response as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
println("Error: \(error!) \(error!.userInfo!)")
}
}
What I see in the console:
Successfully retrieved 2 scores.
Here are the flower names: Optional((
rose,
"sunflower"
))
Maybe there is also an error in my cloude code. Here you can see what I've done:
Parse.Cloud.define("TopTwo", function(request, response) {
var query = new Parse.Query("Flowers");
console.error("Get flowers with the rating: " + request.params.rating);
query.equalTo("stars", request.params.rating);
query.find({
success: function(results) {
console.error("Results: " + results);
var list = [];
for (i = 0; i < results.length; i++) {
list[i] = results[i].get('flowerName');
}
console.error("Flower name list: " + list);
response.success(list);
},
error: function() {
response.error("lookup failed");
}
});
});
And here the parse logs:
Results: [object Object],[object Object]
Flower name list: rose,sunflower
(I'm using XCode 6.3.2 - Swift 1.2)
Many thanks in advance!
Okay, I could solve it on my own.
The object which is returned from cloud code is already an Array. Therefore a casting into NSArray has to be made instead of a casting into [PFObject].
Here is the working Swift code:
PFCloud.callFunctionInBackground("dayTopFive", withParameters: ["day":1]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(response!.count) scores.")
// This is working:
let objects = response as! NSArray
for object in objects {
println("A top flower is: \(object)")
}
}
}

Facebook SDK iOS with Swift - Requesting for Friend List - Explanation of the Method

Would anyone be able to explain this method that we should invoke to recieve the friend list?
var fbRequestFriends: FBRequest = FBRequest.requestForMyFriends()
fbRequestFriends.startWithCompletionHandler{
(connection:FBRequestConnection!,result:AnyObject?, error:NSError!) -> Void in
}
Specifically this line
(connection:FBRequestConnection!,result:AnyObject?, error:NSError!) -> Void in
It seems to me like we are calling a function "startWithCompletionHandler", after that I am lost to be honest. I can't understand what happens next. Can anyone please explain this?
Edit:
I understand this is the way to implement it. I'm Actually looking for an intuitive explanation like in this answer:
Method Syntax in Objective C
you can use below code to get the friend list
// Get List Of Friends
var friendsRequest : FBRequest = FBRequest.requestForMyFriends()
friendsRequest.startWithCompletionHandler
{
(connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
var resultdict = result as NSDictionary
println("Result Dict: \(resultdict)")
var data : NSArray = resultdict.objectForKey("data") as NSArray
for i in 0 ..< data.count
{
let valueDict : NSDictionary = data[i] as NSDictionary
let id = valueDict.objectForKey("id") as String
println("the id value is \(id)")
}
var friends = resultdict.objectForKey("data") as NSArray
println("Found \(friends.count) friends")
}
Well you can see the result of your request call in the closure that you are passing in . Try printing the result object to console like below .
var fbRequestFriends: FBRequest = FBRequest.requestForMyFriends()
fbRequestFriends.startWithCompletionHandler{
(connection:FBRequestConnection!,result:AnyObject?, error:NSError!) -> Void in
if error == nil && result != nil {
println("Request Friends result : \(result!)")
} else {
println("Error \(error)")
}
}
I have not worked with Swift sdk for Facebook yet but I think result object should be an array of facebook user objects ( friends ) .

What cause of 'formal parameter name expected' occured in this case?

I run the code below and I got an error without any stack trace.
My code:
typedef Check<T>(T value, [onError(T value)]);
main () {
List<Check> checks = [
(str) => str != null,
(str) => !str.isEmpty
];
Check<String> doCheck = (String value, [onError(String)]) {
checks.forEach((Check check) {
if (?onError) {
check(value, onError);
} else {
check(value);
}
});
};
doCheck("10");
}
And, the error I got.
file:///..()../sample.dart': Error: line 11 pos 12: formal parameter name expected
if (?onError) {
I want to get onError as an optional parameter in doCheck function, and pass this parameter to other functions in checks.
I confirmed to forward an optional parameter to 'one' function...
Is this one of restrictions to optional parameters?
I would say it is a bug (see issue 8007). To work around it, you have to use a temporary variable :
typedef Check<T>(T value, [onError(T value)]);
main () {
List<Check> checks = [
(str) => str != null,
(str) => !str.isEmpty
];
Check<String> doCheck = (String value, [onError(String)]) {
final isOnErrorPresent = ?onError;
checks.forEach((Check check) {
if (isOnErrorPresent) {
check(value, onError);
} else {
check(value);
}
});
};
doCheck("10");
}

Resources