Why do I get “Value of type 'UnsafePointer<_>' has no member 'baseAddress'”? - swift

I modified the hashing function from this answer https://stackoverflow.com/a/25391020/10551293 a bit and it gives me an error.
Value of type 'UnsafePointer<_>' has no member 'baseAddress'
import Foundation
import CommonCrypto
extension Data {
func sha512() -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
self.withUnsafeBytes {
_ = CC_SHA512($0.baseAddress!, CC_LONG(self.count), &hash)
}
return Data(hash)
}
}
I tried googling it but I got no helpful results.
Why is this?

Related

How to decode an array from an api

I have the following response from an API :
[803442,1605299,1605300,1880804,1880806,1880808,1880810,1880811,1880817,1880819,1880820,1880825,1880826,1880828,1880829,1880830,1880831,1880832,1880833,1880834,1880835,1880836,1880844,1880847,1880849,1880850,1880851,1880862,1880863,1880864]
Just an array of Int
I'm trying to decode it using the JSONDecoder but since it does not have a name its confusing me.
If I have something like this
{"results":[{"device_id":4085245,"locations":[{"time":1553285663,"lat":2.8019,"lon":-60.7276,"accuracy":80,"seq_number":722},{"time":1553328699,"lat":2.8025,"lon":-60.7266,"accuracy":14503,"seq_number":723}]}]}
I know how to do it since I can build the structure like this
struct results: Decodable {
var device_id: Int
var locations: [locations]
}
struct locations: Decodable {
var time: Int
var lat: Double
var lon: Double
var accuracy: Double
var seq_number: Int
}
But on the first case I don't know how to do it.
Does anyone have a suggestion please.
Thank you
Int is already Decodable, so you can easily decode array of this type
do {
let array = try JSONDecoder().decode([Int].self, from: data)
} catch { print(error) }
Its an Array of Int. Since both Int and Array are already Codable you can just directly decode it. Example Playground:
import UIKit
import PlaygroundSupport
let data = "[803442, 1605299, 1605300, 1880804, 1880806, 1880808, 1880810, 1880811, 1880817, 1880819, 1880820, 1880825, 1880826, 1880828, 1880829, 1880830, 1880831, 1880832, 1880833, 1880834, 1880835, 1880836, 1880844, 1880847, 1880849, 1880850, 1880851, 1880862, 1880863, 1880864]".data(using: .utf8)!
if let decoded = try? JSONDecoder().decode([Int].self, from: data) {
print(decoded)
}

Vapor Swift Fluent : Type of expression is ambiguous without more context

This is my route :
router.get("answers","delete", Int.parameter) { req -> Future<Response> in
let answerID = try req.parameters.next(Int.self)
guard let _ = getUsername(req) else {
throw Abort(.unauthorized)
}
return Message.query(on: req).filter(\.id == answerID).first().map(to: Response.self) { answer in
guard let answer = answer else {
throw Abort(.notFound)
}
return answer.delete(on: req).map(to: Response.self) { _ in
return req.redirect(to: "/answers")
}
}
}
But for xCode this is Ambiguous without more context .filter(\.id == answerID)
And this is my struct Message :
struct Message: Content, SQLiteUUIDModel, Migration {
var id: UUID?
var username: String
var content: String
var category: String
var question: String
var date: Date
}
I don't understand because I use filters on ids in many other routes and it's the first time I show this error.
I googled this and it seems that the errors shows up when Fluent is not imported but I've already import Fluent at the top.
I just had time to test your code. If you replace
... .map(to: Response.self) { answer in ....
with
... .flatMap(to:Response.self) { answer in ...
it works.

Swift - Cannot convert value of type 'UnsafePointer<Any>' to expected argument type 'UnsafePointer<_>'

I am trying to use CommonCrypto (with the help of https://github.com/sergejp/CommonCrypto) for the first time with swift. Here is my code:
UnsafeRawPointer(ivData!.withUnsafeBytes
{(pointer) -> UnsafePointer<Any> in
let ivBuffer = pointer
})
The error is:
Cannot convert value of type 'UnsafePointer' to expected argument
type 'UnsafePointer<_>'
What does the <_> signify? What do I need to do? Thanks.
It's pointer that it is complaining about. You need to cast it. Here's an example usage, part of creating an MD5 hash:
var rawBytes = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
let _ = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
CC_MD5(bytes, CC_LONG(data.count), &rawBytes)
}
This is how I needed to do it in my context
let preBuffer = ivData!.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
return bytes
}
let ivBuffer = UnsafeRawPointer(preBuffer)

Alamofire for loop returns empty array in Playgrounds

I've searched for the last hour and I can't seem to figure this out. I'm throwing in the towel and asking.
I have the following playground script below, and it prints an empty array.
I would like to return an array of custom objects when the function is called. I read that Alamofire is aynchronous, but I really don't know what to do at this point.
Thanks in advance!
//: Playground - noun: a place where people can play
import UIKit
import Alamofire
import SWXMLHash
import PlaygroundSupport
import Foundation
PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
class Tram {
var arrivalInMinutes: Int?
var tramDestinationEnglish: String?
init(destination: String, arrivalTime: Int) {
tramDestinationEnglish = destination
arrivalInMinutes = arrivalTime
}
}
func retrieveListOfTrams() -> [Tram] {
var anyArray = [Tram]()
Alamofire.request("https://hktramways.com/nextTram/geteat.php?stop_code=08W")
.response { (response) in
let xmlData = SWXMLHash.parse(response.data!)
for elem in xmlData["root"]["metadata"].all {
let tramArrival = elem.element!.attribute(by: "arrive_in_minute")!.text
let tramDestination = elem.element!.attribute(by: "tram_dest_en")!.text
anyArray.append(Tram(destination: tramDestination, arrivalTime: Int(tramArrival)!))
}
}
return anyArray
}
print(retrieveListOfTrams())
The problem is that you're returning the array before your request return a result, because as you read Alamofire have an asynchronous behavior. One way to solve this is by having a completion block that will only return the array after the result arrives:
func retrieveListOfTrams(completion: #escaping ([Tram]) -> Void) {
var anyArray = [Tram]()
Alamofire.request("https://hktramways.com/nextTram/geteat.php?stop_code=08W")
.response { (response) in
let xmlData = SWXMLHash.parse(response.data!)
for elem in xmlData["root"]["metadata"].all {
let tramArrival = elem.element!.attribute(by: "arrive_in_minute")!.text
let tramDestination = elem.element!.attribute(by: "tram_dest_en")!.text
anyArray.append(Tram(destination: tramDestination, arrivalTime: Int(tramArrival)!))
}
completion(anyArray)
}
}
Then you can call the function:
retrieveListOfTrams(completion: { anyArray in
print(anyArray.description)
})

[Error]: object not found for update Swift + Parse.com

Class Name : Product
Column Name : Likes
i print 1 and 2 just for check
var objectID = "wbgNSvui5b" //object are exist in my database
var query = PFQuery(className:"Product")
var P = query.getObjectWithId(objectID)
P.incrementKey("Likes")
P.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
println("1")
// The score key has been incremented
} else {
println("2")
// There was a problem, check error.description
}
}
always print 2 with object not found for update (Code: 101, Version: 1.7.4)
I don't think you can do a line break in your closure syntax between your method name and the return values (I think the in needs to be the last thing before the line break). Maybe you just formatted your code for Stack Overflow, but just thought I'd mention this:
P.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success{
println("success")
}else{
println(error!.localizedDescription)
}
}
Good luck. :)

Resources