This question already has answers here:
How to get device make and model on iOS?
(23 answers)
Closed 3 years ago.
I've been searching a while about this and I've found out that this can't be get from UIDevice.current.model, because it returns just iPhone. there were several answers pointing to this code:
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
return simulatorModelIdentifier
}
var sysinfo = utsname()
uname(&sysinfo) // ignore return value
let deviceModel = String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)?.trimmingCharacters(in: .controlCharacters)
return deviceModel ?? ""
by the way I'm not sure that this uses public or private api and it seems like private api for me.
Question
is this code using any private api?
Your code does not use any private API.
uname function returns a POSIX structure containing name and information about current kernel. The machine variable contains an hardware identifier. You'll need to convert this identifier to a more friendly name, but that's all.
You can use man uname in your terminal for more information about the function.
Related
This question already has answers here:
Generate UUID from name space?
(2 answers)
Closed 5 days ago.
I am having string that i want to convert UUID
my string is - > "43pszizx-0000-0000-0000-000000000000"
i want to convert this into UUID
i have tried this code
let contactUUID = "43pszizx-0000-0000-0000-000000000000"
if let uuid = UUID(uuidString: contactUUID) {
moviesVC.conversationID = uuid
}
but it always returns nil
is there any solution to convert this string to UUID, this string coming from API as a contactId
thanks in advance
As per the doc
Returns nil if the string isn’t a valid UUID representation.
let contactUUID = "43pszizx-0000-0000-0000-000000000000"
//The string representation of a UUID, such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F.
But the contactUUID doesn't seems to be matching with UUID representation so its always returning nil
This question already has an answer here:
How can I decode a JSON response with an unknown key in Swift?
(1 answer)
Closed 3 years ago.
I want to decode the following object from the server
{"USD":6385.74,"JPY":715249.73,"EUR":5582.36}
but I want to use a decodable struct with unknown key and value.Is this possible?
Regards,
Spyros
You can try
let res = try? JSONDecoder().decode([String:Double].self,from:data)
print(res["USD"])
which will enable you to decode any key
When I work with JSONs that are not fully known (as in I know all the possible keys and need all of them) I used SwiftyJSON library: https://github.com/SwiftyJSON/SwiftyJSON
It's much easier to work with than the built in JSON decoder
in your case it would be:
var jsonString = "{\"USD\":6385.74,\"JPY\":715249.73,\"EUR\":5582.36}"
let json = JSON(parseJSON: jsonString)
then you can do a bunch of stuff like iterating over keys
for (key, value) in json {
if let currency = key.string {
print (currency,value)
}
}
Check out the documentation in https://github.com/SwiftyJSON/SwiftyJSON
This question is about Swift.
It's very easy to generate a rfc UUID in Swift getting a Swift String as at this stage Apple have made a Swift method for it...
func sfUUID()->String
{
return UUID().uuidString.lowercased()
}
I need an old-style "version 1" UUID, when using Swift
(Example: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_.28date-time_and_MAC_address.29)
Is there a way to do this in Swift3? ( >9 only)
In Swift, how to get a Version 1 UUID. So, there might be some option I don't know about on the UUID() call, or there's the difficulty of calling a C call and getting the result safely as a String.
Callam's link is the actual answer. Swift can (and in this case must) call C, so the name of the C function is all you really need.
But the "Swift" question here is just how to call a C function from Swift, which is a general skill that's more important than this particular question (and isn't really well explained in the current documentation). So it's worth studying how the following works, and not taking it as just the answer to "how do you generate a v1 UUID in Swift."
var uuid: uuid_t = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) {
uuid_generate_time($0)
}
}
let finalUUID = UUID(uuid: uuid)
This is incredibly out of date. Don't do this any more.
I'd delete the answer, but it's ticked!
Swift code which gets to the C call...
func generateVersionOneAkaTimeBasedUUID() -> String {
// figure out the sizes
let uuidSize = MemoryLayout<uuid_t>.size
let uuidStringSize = MemoryLayout<uuid_string_t>.size
// get some ram
let uuidPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: uuidSize)
let uuidStringPointer = UnsafeMutablePointer<Int8>.allocate(capacity: uuidStringSize)
// do the work in C
uuid_generate_time(uuidPointer)
uuid_unparse(uuidPointer, uuidStringPointer)
// make a Swift string while we still have the C stuff
let uuidString = NSString(utf8String: uuidStringPointer) as? String
// avoid leaks
uuidPointer.deallocate(capacity: uuidSize)
uuidStringPointer.deallocate(capacity: uuidStringSize)
assert(uuidString != nil, "uuid (V1 style) failed")
return uuidString ?? ""
}
This question already has an answer here:
In Swift, does Int have a hidden initializer that takes a String?
(1 answer)
Closed 7 years ago.
I'm new to Swift. I saw this code online:
let number = Int("123")
I want to read a bit more about the "Int" type initialiser that take a string as a argument. However, when I looked at Apple's offical Swift documentations:
https://developer.apple.com/library/tvos/documentation/Swift/Reference/Swift_Int_Structure/index.html#//apple_ref/swift/struct/s:Si
I couldn't find a Int type initialiser that actually takes a string as its argument. Am I looking at the wrong place? Or is there something I'm missing or unaware of?
If you click on init(_:radix:) to expand the declaration then you'll see
Construct from an ASCII representation in the given radix.
Declaration
init?(_ text: String, radix radix: Int = default)
The first parameter is a string (and has an empty external parameter
name). The second parameter "radix" has a default value,
therefore it can be omitted when calling the function:
let number = Int("123")
but you can specify the radix to create a number from a string
representation in another base:
let numberFromHexString = Int("100", radix: 16) // Optional(256)
let numberFomOctalString = Int("077", radix: 8) // Optional(63)
There is also a "trick" which I learned at
"Jump to definition" for methods without external parameter names: If you write
let number = Int("123")
as
let number = Int.init("123")
then you can "command-click" on "init" in Xcode, and you are led
directly to the declaration
public init?(_ text: String, radix: Int = default)
This question already has answers here:
Cannot invoke `join` with an argument list of type (String, [String]) in Swift 2.0
(2 answers)
Closed 6 years ago.
I am facing a problem during the development of my iOS application, what I am trying to achieve is to create a single string from an array of strings. The array contains the address of a given location, obtained from a reverse geocoding using CLGeocoder, this is the code that gives me the array of strings:
let userCoordinates = CLLocation(latitude: mapView.userLocation.location!.coordinate.latitude, longitude: mapView.userLocation.location!.coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(userCoordinates, completionHandler: {
placemark, error in
let reverseGeocodedLocation = placemark?.first?.addressDictionary?["FormattedAddressLines"] as? [String]
}
reverseGeocodedLocation in my case is:
["Apple Inc.", "Cupertino, CA 95014", "United States"]
The result string should separate the strings in the array and present them in a multi-line format like this:
Apple Inc.
Cupertino, CA 95014
United States
I have tried searching on the web for a solution and I found this code that should do that, and this could be the solution:
print("\n".join(reverseGeocodedLocation.map({$0})))
But the compiler says:
Cannot invoke 'join' with an argument list of type '([String]?)'
if let reverseGeocodedLocation = reverseGeocodedLocation {
print(reverseGeocodedLocation.joinWithSeparator("\n"))
}
As an answer instead of a comment.
Swift 3/4:
reverseGeocodedLocation.joined(separator: "\n")