Swift compile errors when uploading file using NSFileHandle with Dropbox API - dropbox-api

I'm trying to use the example where a file is uploaded using NSFileHandle. I get the following compile errors:
I get this 2 times:
Cannot invoke 'uploadSessionStart' with an argument list of type '(input: NSData?)'
I get the errors once in uploadFirstChunk() and once in uploadNextChunk(), both times in this statement:
var data : NSData? = nil
...
data = fileHandle!.readData(ofLength: chunkSize) as NSData?
...
dbClient.files.uploadSessionStart(input: data)<==
I also get this error in uploadNextChunk():
Type of expression is ambiguous without more context
This is the statement where it occurs:
let destPath = "/MDG/test/Test1.mp4"
...
dbClient.files.uploadSessionFinish(
cursor: Files.UploadSessionCursor(sessionId: self.sessionId, offset: UInt64(offset)),
commit: Files.CommitInfo(path: destPath),<==
input: data!)

Related

Can't unarchive custom Object with NSKeyedUnarchiver in AR Multiuser

I'm using MultipeerConnectivity to share SCNNodes position in a multiuser AR session.
When I archive (with NSKeyedArchiver.archivedData(withRootObject: someARNode, requiringSecureCoding: true) )
And unarchive (with if let node = try NSKeyedUnarchiver.unarchivedObject(ofClass:SCNNode.self, from: data) {)
Everything works fine, but now I'm trying to send a custom Object like this:
struct ARUser: Codable {
var idUser : String
var position: [Double]
}
When I try to unarchive the object received with the NSKeyedUnarchiver.unarchivedObject it let me error.
if let node = try NSKeyedUnarchiver.unarchivedObject(ofClass:ARUser.self, from: data) {...}
I get the syntax error: Incorrect argument label in call (have 'ofClass:from:', expected 'ofClasses:from:')
But if I change the function as suggested by the compiler:
if let node = try NSKeyedUnarchiver.unarchivedObject(ofClasses:[ARUser.self], from: data) {..}
I get the next syntax error: Cannot convert value of type 'ARUser.Type' to expected element type 'AnyObject.Type'
So, the question here is, what's the correct way to unarchive custom Objects?
Since here you use Codable
struct ARUser: Codable {
Then
do {
let dataToObject = try JSONDecoder().decode(ARUser.self,from:data)
let objectToData = try JSONEncoder().encode(dataToObject)
}
catch {
print(error)
}
NSKeyedUnarchiver is an old Objective-C stuff

Swift MessageKit - Cannot Convert value of type '_?' to expected argument type 'URL?'

I have just begun using MessageKit and have updated my code to 4.2 in swift and have been solving the problems. Yet, I am using the Firebase chat tutorial and have come across problems in the sample code that are throwing errors that aren't visible in the sample project.
Cannot convert value of type '_?' to expected argument type 'URL?'
completion(meta?.downloadURL())
Assuming that your problem is probably the following
storage.child(channelID).child(imageName).putData(data, metadata: metadata) { meta, error in
completion(meta?.downloadURL())
}
Answer, swift 4
storage.child(channelID).child(imageName).putData(data, metadata: metadata) { metaN, error in
// then we check if the metadata and path exist
// if the error was nil, we expect the metadata and path to exist
// therefore if not, we return an error
guard let metadata = metaN, let path = metadata.path else {
completion(nil)
return
}
// now we get the download url using the path
// and the basic reference object (without child paths)
self.getDownloadURL(from: path, completion: completion)
}
private func getDownloadURL(from path: String, completion:#escaping (URL?) -> Void) {
let firebaseStorageUrl = "gs://yourApp-Firebase-Storage.appspot.com"
let storageReference = Storage.storage().reference(forURL: firebaseStorageUrl)
storageReference.child(path).downloadURL { (url, error) in
completion(url)
}
}
Be sure that you have enabled Storage in Firebase and check console errors if fails

Swift 3 change to NSErrorPointer?

I have code I've been using for SwiftyJSON and I'm trying to update to Swift 3 using XCode 8.0 Beta 3. I'm running into an issue where the compiler doesn't like the argument 'error: &err' as it did before. I've been searching for how to correctly pass an NSErrorPointer but everything I've found says to re-write, leave out the error and throw an error back. Since this isn't my code I'd rather leave it as it is. So what's the correct new way to use an NSErrorPointer?
var err : NSError?
// code to get jsonData from file
let json = JSON(data: jsonData, options: JSONSerialization.ReadingOptions.allowFragments, error: &err)
if err != nil {
// do something with the error
} else {
return json
}
The code above results in compiler error: '&' can only appear immediately in a call argument list. I've tried creating an NSErrorPointer so I can use that instead but I can't find anything on how to initialize one (the type alias declaration is not enough). I've already been to Using Swift with Cocoa and Obj-C, it does not contain the word NSErrorPointer, instead goes over the new way of throwing errors. I've also looked over a couple dozen posts all using the &err so apparently this is new to Swift 3.
Is there anyone out there that's solved this one? What's the answer to using NSErrorPointer?
Thanks,
Mike
That seems to be an error in the Swift 3 branch of SwiftyJSON at
https://github.com/SwiftyJSON/SwiftyJSON/blob/swift3/Source/SwiftyJSON.swift
which defines the init method as
public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer? = nil) {
do {
let object: AnyObject = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error??.pointee = aError
}
self.init(NSNull())
}
}
In the Swift 3 that comes with Xcode 8 beta 3, NSErrorPointer is an optional:
public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>?
as a consequence of
SE-0055: Make unsafe pointer nullability explicit using Optional
Therefore the error parameter should have the type NSErrorPointer,
not NSErrorPointer? (and consequently error??.pointee
changed to error?.pointee).
With these changes the init method becomes
public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error?.pointee = aError
}
self.init(NSNull())
}
}
and then your code compiles and runs as expected.

countForFetchRequest in Swift 2.0

I am trying to use the countForFetchRequest method on a managed object context in Swift 2.0.
I note that the error handling for executeFetchRequest has been changed across to the new do-try-catch syntax:
func executeFetchRequest(_ request: NSFetchRequest) throws -> [AnyObject]
but the countForFetchRequest method still uses the legacy error pointer:
func countForFetchRequest(_ request: NSFetchRequest,
error error: NSErrorPointer) -> Int
...and I am having a bit of trouble figuring out how to use this in Swift 2.0.
If I do the same thing as pre-Swift 2.0:
let error: NSError? = nil
let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
I get errors saying to remove the &, but if I remove that I get another error saying that NSError cannot be converted to an NSErrorPointer.
Any help would be appreciated about how to get this working.
Your code is almost correct, but error needs to be a variable, in order to be passed as
inout-argument with &:
var error: NSError? = nil
let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
Update: As of Swift 3, countForFetchRequest
throws an error:
do {
let count = try managedObjectContext.context.count(for:fetchRequest)
return count
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
return 0
}
You need to do like this:
let error = NSErrorPointer()
let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
print("Count \(fetchResults)")
This is the code for Swift 2.0

SwiftyJSON upgrading to Swift 2.0 requires to explicitly call .dictionary getter to access values?

In Xcode 6.4 I wrote a simple program in Swif 1.2
by using SwiftyJSON
to parse an HAR i.e: a JSON-formatted archival format for logging HTTP where everything worked great.
Updating to Xcode 7 and Swift 2.0 I also update the SwiftyJSON dependency
, but this broke my program when it tries to access JSON values by a compact syntax like this:
let harVersion = mJSON["log"]["version"].string
In current update this syntax give the following runtime error:
Could not cast value of type 'Swift.String' (0x1002bf218) to 'Swift.Int' (0x100869aa8).
I solved by changing/refactoring the code by adding .dictionary explicitly:
let harVersion = mJSON.dictionary!["log"]!.dictionary!["version"]!.string
I would like to know/understand in details the cause of this behavior and if there is a more elegant/robust/concise way to access JSON values. Any advice is appreciated.
Additional information:
Podfile
platform :osx, '10.11'
use_frameworks!
target 'prova-xcode7-swiftcli' do
pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
end
Main.swift:
var request = NSURLRequest(URL: mURL!)
var response: NSURLResponse?
var error: NSError?
var data: NSData? = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) // , error: &error)
if let httpResponse = response as? NSHTTPURLResponse {
if data != nil {
var mJSON = JSON(data: data!)