question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I'm trying to use google/protobuf/timestamp.proto in with gRPC plugin and Go. This is how I run protoc: protoc -I ./ ./*.proto --go_out=plugins=grpc:. And this is my .proto: #domain.proto syntax = "proto3"; option java_multiple_files = true; option java_package = "com.viant.xyz"; option java_outer_classname = "doma...
Add /usr/local/include to include paths to use /usr/local/include/google/api/timestamp.proto: protoc -I/usr/local/include -I. --go_out=plugins=grpc:. *.proto As you can see in timestamp.proto, Timestamp exists in package google.protobuf, so you have to modify to use Timestamp like this: message Foo { google.protob...
gRPC
40,025,602
18
I have a grpc server / client that today will occasionally hang, causing issues. This is being called from a Flask application which is checking in with a background worker process to make sure it's alive / functioning. To make the request to the gRPC server, I have: try: health = self.grpc_client.Health(self.h...
timeout is an optional keyword parameter on RPC invocation so you should change health = self.grpc_client.Health(self.health_ping) to health = self.grpc_client.Health(self.health_ping, timeout=my_timeout_in_seconds) .
gRPC
43,869,397
17
Looking at gRPC Java doc - ManagedChannelBuilder, there're two options to manage the connections. It seems idleTimeout() is the default/preferred configuration. But when I tried to search for a comparison, most of the posts are talking about keepAlive option. I'm curious about what's the common practise and what are t...
Use keepalive to notice connection failures while RPCs are in progress. Use idleTimeout to release resources and prevent idle TCP connections from breaking when the channel is unused. idleTimeout is preferred over keepAliveWithoutCalls because it tends to reduce the overall load in the system. keepAliveWithoutCalls is ...
gRPC
57,930,529
17
Does gRPC support generating documentation for services like Swagger?
protoc-gen-doc is a protoc plugin which generates HTML docs using Go HTML templates. Although it isn't being used by the original sponsor company anymore, it looks like a good starting point.
gRPC
31,819,324
16
In the examples of the GRPC client there are two types of implementation, one where the .proto files are loaded and processed at runtime, and one where they are compiled using protoc. My question is: what is the difference? The docs say nothing more than 'they behave identically', but surely there has to be a differen...
Fundamentally, the primary difference is the one you mentioned: with the dynamic code generation, the .proto file is loaded and parsed at run time, and with static code generation, the .proto file is preprocessed into JavaScript. The dynamic code generation is simpler to use, potentially easier to debug, and generates ...
gRPC
43,216,248
16
The gRPC C++ API for creating channels returns a shared_ptr. The generated function NewStub returns a unique_ptr. However I've seen reports of people having issues trying to create multiple instances of a stub type, sharing a channel. Their solution was to share the stub. It is not clear from the documentation or API i...
I think first we need to clarify the definitions for channel and stub, according to the official documents : channel : A gRPC channel provides a connection to a gRPC server on a specified host and port... Conclude : A channel represents a single TCP connection. stub : On the client side, the client has a local objec...
gRPC
47,022,097
16
How does golang grpc implementation handle the server concurrency? One goroutine per method call? Or sort of goroutine pool? Does it depend on the concurrency model of net/http2?
One goroutine per method call. There's current no goroutine pool for service handlers. It doesn't depend on net/http2 concurrency model. https://github.com/grpc/grpc-go/blob/master/Documentation/concurrency.md#servers
gRPC
50,365,652
16
I want to use gRPC to let clients subscribe to events generated by the server. I have an RPC declared like so: rpc Subscribe (SubscribeRequest) returns (stream SubscribeResponse); where the returned stream is infinite. To "unsubscribe", clients cancel the RPC (btw. is there a cleaner way?). I have figured out how the ...
I found the answer myself. You cast the StreamObserver passed to subscribe to a ServerCallStreamObserver, which exposes methods isCancelled and setOnCancelHandler. scso = ((ServerCallStreamObserver<SubscribeResponse>) responseObserver); scso.setOnCancelHandler(handler); // or if (scso.isCancelled()) { // do whatever...
gRPC
54,588,382
16
grpc fails to connect even when I set my jest test() async function to a 100000ms cap before it times out. // terminal, after running jest --watch ● creates new record 14 UNAVAILABLE: failed to connect to all addresses at Object.<anonymous>.exports.createStatusError (node_modules/grpc/src/common.js:91:15) ...
That gRPC error means that no server is running at the address you are trying to connect to, or a connection to that server cannot be established for some reason. If you are trying to connect to a local Firestore emulator, you should verify that it is running and that you can connect to it outside of a test.
gRPC
59,823,424
16
At my company we're about to set up a new microservice architecture, but we're still trying to decide which protocol would be best for our use case. In our case we have some services that are called internally by other services, but are also exposed via a GraphQL API gateway towards our clients. Option 1: gRPC gRPC see...
It depends on the overall architecture you are implementing. I would suggest to use both GraphQL and gRPC: Use Apollo Federation as a border node to seamlessly handle the requests from your frontends talking in GraphQL. Use CQRS pattern on your API and microservices, and strictly separate the read model from the writ...
gRPC
66,241,844
16
I have a Go gRPC client connected to a gRPC server running in a different pod in my k8s cluster. It's working well, receiving and processing requests. I am now wondering how best to implement resiliency in the event that the gRPC server pod gets recycled. As far as I can ascertain, the clientconn.go code should handle ...
The RPC connection is being handled automatically by clientconn.go, but that doesn't mean the stream is also automatically handled. The stream, once broken, whether by the RPC connection breaking down or some other reason, cannot reconnect automatically, and you need to get a new stream from the server once the RPC con...
gRPC
66,353,603
16
I need to call a celery task for each GRPC request, and return the result. In default GRPC implementation, each request is processed in a separate thread from a threadpool. In my case, the server is supposed to process ~400 requests in batch mode per second. So one request may have to wait 1 second for the result due t...
As noted by @Michael in a comment, as of version 1.32, gRPC now supports asyncio in its Python API. If you're using an earlier version, you can still use the asyncio API via the experimental API: from grpc.experimental import aio. An asyncio hello world example has also been added to the gRPC repo. The following code i...
gRPC
38,387,443
15
In gRPC you can define a method like service HelloService { rpc SayHello (HelloRequest) returns (HelloResponse); } or service HelloService { rpc SayHello (HelloRequest) returns (HelloResponse) {} } (from http://www.grpc.io/docs/guides/concepts.html#service-definition). I've looked through the docs and there does...
I'm not an expert but I will try to explain it You can add custom options in your rpc definitions For example if you use grpc-gateway that allows you to translate the RESTful API into gRPC In this snippet I'm requesting the body field and the RESTful call will be in /api/{client} for example: service Builder { rpc Ge...
gRPC
43,771,925
15
We are using grpc as the RPC protocol for all our internal system. Most of the system is written in Java. In Java, we can use InprocessServerBuilder for unittest. However, I haven't find a similar class in Python. Can any one provide a sample code for how to do GRPC unittest in python?
How serendipitous that you have asked this question today; our unit test framework just entered code review. So for the time being the way to test is to use the full production stack to connect your client-side and server-side code (or to violate the API and mock a lot of internal stuff) but hopefully in days to weeks ...
gRPC
44,718,078
15
I am trying to keep a Grpc server running as a console daemon. This gRPC server is a microservice that runs in a docker container. All of the examples I can find make use of the following: Console.ReadKey(); This does indeed block the main thread and keeps it running but does not work in docker with the following erro...
You can now use Microsoft.Extensions.Hosting pacakge which is a hosting and startup infrastructures for both asp.net core and console application. Like asp.net core, you can use the HostBuilder API to start building gRPC host and setting it up. The following code is to get a console application that keeps running until...
gRPC
45,989,148
15
I could successfully run a gRPC client and gRPC server in c++ now I wish to establish a communication between node A and gRPC server i.e. node B as in the attached image. Are there any examples which I can refer to below is what I am looking for. I have this node A with http message (GET method) which I need to parse ...
Most of the times, if you have to use HTTP to contact a gRPC node, it most likely means that A is in fact a browser or browser-like environment, since you can simply instantiate a gRPC client on pretty much anything else. If that's your situation, then I'd suggest having a look at grpc-web which aims to address that sp...
gRPC
49,852,761
15
I've read the tutorial and I'm able to generate the .cs file but it doesn't include any of my service or rpc definitions. I've added protoc to my PATH and from inside the project directory. protoc project1.proto --csharp_out="C:\output" --plugin=protoc-gen-grpc="c:\Users\me\.nuget\packages\grpc.tools\1.8.0\tools\window...
You need to add the --grpc_out command line option, e.g. add --grpc_out="C:\output\" Note that it won't write any files if you don't have any services. Here's a complete example. From a root directory, create: An empty output directory A tools directory with protoc.exe and grpc_csharp_plugin.exe A protos directory wi...
gRPC
50,687,335
15
When launching a Python grpc.server, what's the difference between maximum_concurrent_rpcs and the max_workers used in the thread pool. If I want maximum_concurrent_rpcs=1, should I still provide more than one thread to the thread pool? In other words, should I match maximum_concurrent_rpcs to my max_workers, or should...
If your server already processing maximum_concurrent_rpcs number of requests concurrently, and yet another request is received, the request will be rejected immediately. If the ThreadPoolExecutor's max_workers is less than maximum_concurrent_rpcs then after all the threads get busy processing requests, the next request...
gRPC
51,089,746
15
I can't make a request using Google TTS Client library in java. Each time it throws a bunch of exceptions. I just try to get a list of available voices. GoogleCredentials creds = null; TextToSpeechClient textToSpeechClient = null; try { creds = GoogleCredentials.fromStream(new FileInputStream(creds...
If you're using Gradle with the ShadowJar plugin, this is all you need to get it to merge the contents of service files from the various gRPC libraries: shadowJar { mergeServiceFiles() } Discovered from a thread here.
gRPC
55,484,043
15
I have added below new code in protobuf file and compiled to get the generated grpc_pb files. service EchoService { rpc Echo(EchoMessage) returns (EchoMessage) { #-----New code start----- option (google.api.http) = { post: "/v1/echo" body: "*" }; #-----New code end------ } } From cURL c...
In order to test gRPC server without client, we have to use grpcurl not curl. Please take a look at https://github.com/fullstorydev/grpcurl However, based on my experience there is a requirement to make it works. First, please ensure that your service support Reflection, you can read about it from https://github.com/so...
gRPC
56,580,535
15
I am trying to build a grpc web client and I need to pack the code to resolve the require statements. I have compiled the protos to js and it works if I have them in the current folder where I have installed the node modules. The problem is if I have the compiled proto in some other place and I require them from there...
You can specify resolve.modules to customize the directory, where Webpack searches for modules with absolute import paths: // inside webpack.config.js const path = require('path'); module.exports = { //... resolve: { modules: [path.resolve(__dirname, 'node_modules'), 'node_modules'] } }; This will let node_m...
gRPC
57,544,105
15
Even though every python grpc quickstart references using grpc_tools.protoc to generate python classes that implement a proto file, the closest thing to documentation that I can find simply says Given protobuf include directories $INCLUDE, an output directory $OUTPUT, and proto files $PROTO_FILES, invoke as: $ python...
I thought you are asking about the Python plugin. Did you try -h? $ python -m grpc.tools.protoc -h Usage: /usr/local/google/home/lidiz/.local/lib/python2.7/site-packages/grpc_tools/protoc.py [OPTION] PROTO_FILES Parse PROTO_FILES and generate output based on the options given: -IPATH, --proto_path=PATH Specify the ...
gRPC
57,909,401
15
I am using gRPC application and building a simple app. Below the files. syntax = "proto3"; option java_multiple_files = true; package com.grpc; message HelloRequest { string firstName = 1; string lastname = 2; } message HelloResponse { string greeting = 1; } service HelloService { rpc hello(HelloReques...
If you're running grpcox as a docker container, you'll need to give the container either host network access (easiest) so that it can access the server running on the host's (!) port 9901 i.e. localhost:9901, or provide it with a DNS address that it can resolve the address your host, i.e. your-host:9901. For host netwo...
gRPC
64,139,243
15
i'm trying to implement pub sub pattern using grpc but i'm confusing a bit about how to do it properly. my proto: rpc call (google.protobuf.Empty) returns (stream Data); client: asynStub.call(Empty.getDefaultInstance(), new StreamObserver<Data>() { @Override public void onNext(Data value) { ...
In the implementation of your service: @Override public void data(Empty request, StreamObserver<Data> responseObserver) { observers.add(responseObserver); } You need to get the Context of the current request, and listen for cancellation. For single-request, multi-response calls (a.k.a. Server streaming) the...
gRPC
54,942,240
14
If you are in a middle-ware that both receives the context and maybe append some data to context to send it to the next interceptor, then which of the two methods i.e. metadata.FromOutgoingContext and metadata.FromIncomingContext shall be called?
If you are writing that middle-ware in the server, then you are receiving that metadata in the incoming request. You should then use metadata.FromIncomingContext to get the metadata at that point. The metadata in the "outgoing context" is the one generated by the client when sending an outgoing request to the server. S...
gRPC
57,060,602
14
I have a ASP.NET Core application that has two endpoints. One is the MVC and the other is the Grpc. I need that the kestrel publishs each endpoint on different sockets. Example: localhost:8888 (MVC) and localhost:8889 (Grpc). I know how to publish two endpoints on Kestrel. But the problem is that it's publishing the M...
Here is the configuration that works for me: public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(options => { options.Listen(IPAddress.Loopback, 55001...
gRPC
57,273,862
14
I am using dot net core 3.0. I have gRPC app. I am able to communicate to it through gRPC protocol. I thought my next step would be add some restful API support. I modified my startup class to add controllers, routing etc..... When I try navigating to the API using a browser, I get an error "ERR_INVALID_HTTP_RESPONSE" ...
I found the solution. I didn't mention I was running on MacOS and using Kestrel (and it appears the combination of MacOS AND Kestrel is the problem). I apologize for that missing information. The solution is similar to what is here. I had to add a call to options.ListenLocalhost for the webapi port. here's the code: pu...
gRPC
58,649,775
14
I have two network services - a gRPC client and gRPC server. Server is written in .NET Core, hence HTTP/2 for gRPC is enforced. Client however is a .NET Framework 4.7.2 web app hosted on IIS 8.5, so it only supports HTTP/1.1. Since it will take some time to upgrade the client I was thinking if it is possible to use HTT...
No, you cannot use gRPC on HTTP 1.1; you may be able to use the Grpc.Core Google transport implementation, however, instead of the managed Microsoft bits; this targets .NET Standard 1.5 and .NET Standard 2.0, so should work on .NET Core, and uses an OS-specific unmanaged binary (chttp2) for the transport. For client-s...
gRPC
59,770,763
14
I am trying to learn how to use gRPC asynchronously in C++. Going over the client example at https://github.com/grpc/grpc/blob/v1.33.1/examples/cpp/helloworld/greeter_async_client.cc Unless I am misunderstanding, I don't see anything asynchronous being demonstrated. There is one and only one RPC call, and it blocks on ...
You are right, this is a really bad example, it blocks and not async at all. better look at this example: grpc/greeter_async_client2. Here you can see in the main that they send the rpc messages in a loop in async non-blocking way: Client Async send function: void SayHello(const std::string& user) { // Data we are ...
gRPC
64,639,004
14
I have an implementation of GRPC-java server code, but I didn't find the example code to unit test the StreamObserver. Does anyone know the right way to unit test the function? public class RpcTrackDataServiceImpl implements TrackDataServiceGrpc.TrackDataService { @Override public void getTracks(GetTracksReques...
Unit testing is very straight forward using the InProcess transport mentioned by Eric above. Here is an example a bit more explicit on code: We test a service based on this protobuff definition: syntax = "proto3"; option java_multiple_files = true; option java_package = "servers.dummy"; option java_outer_classname = "...
gRPC
37,552,468
13
I am writing a connection back to a TensorFlow Serving system with gRPC from a C# platform on MS Windows 10. I have seen many references to Time-out and Dead-line with the C++ API for gRPC, but can't seem to figure out how to for a timeout under C#. I am simply opening a channel to the server, setting up a client and ...
To set the deadline for a call, you can simply use the following "deadline:" client.Classify(featureSet, deadline: DateTime.UtcNow.AddSeconds(5)); or client.Classify(featureSet, new CallOptions(deadline: DateTime.UtcNow.AddSeconds(5))); Both ways should be easily discoverable by code completion.
gRPC
37,669,975
13
I am attempting to create a java grpc client to communicate with a server in go. I am new to grpc so am following this tutorial gRPC Java Tutorial. In these examples they refer to blocking and nonblocking stubs which they appear to import from elsewhere in their github. import io.grpc.examples.routeguide.RouteGuideGrpc...
The grpc stub classes are generated when you run the protoc compiler and it finds a service declaration in your proto file. The stub classes are the API your client uses to make rpc calls on the service endpoint. These stubs come in two flavors: blocking and async. Blocking stubs are synchronous (block the currentl...
gRPC
45,371,157
13
I'm following this Route_Guide sample. The sample in question fires off and reads messages without replying to a specific message. The latter is what i'm trying to achieve. Here's what i have so far: import grpc ... channel = grpc.insecure_channel(conn_str) try: grpc.channel_ready_future(channel).result(timeout=5)...
Instead of writing a custom iterator, you can also use a blocking queue to implement send and receive like behaviour for client stub: import queue ... send_queue = queue.SimpleQueue() # or Queue if using Python before 3.7 my_event_stream = stub.MyEventStream(iter(send_queue.get, None)) # send send_queue.put(Streamin...
gRPC
47,831,895
13
My goal is to build an executable using pyinstaller. The python script I am trying to build imports grpc. The following is an example that illustrates the problem called hello.py. import grpc if __name__ == '__main__': print "hello world" I do pyinstaller hello.py and that produces the expected dist directory...
I faced the same issue. I referred this document: gRPC As per the documentation, first upgrade your pip to version 9 or higher. Then use the following commands: $ python -m pip install grpcio $ python -m pip install grpcio-tools It worked for me!
gRPC
48,394,486
13
I'm working on a tutorial about gRPC. When I generated the .pb.go file, I'm getting some XXX_* type in my struct. This is my consignment.proto file: syntax = "proto3"; package go.micro.srv.consignment; service ShippingService { rpc CreateConsignment(Consignment) returns (Response) {} } message Consignment { ...
The XXX_ types are used by the Protobuf library to store unknown fields. When you decode a proto, there may be additional fields in the serialized data that the library doesn't know what to do with. This can happen, for instance, when the reader and writer of the data are using different copies of the proto file. Th...
gRPC
50,704,319
13
I am running a grpc server listening on localhost:6000, exposing 2 grpc services: RegisterSubscriberServiceServer and RegisterDropperServiceServer. Since both of these services are reachable from localhost:6000, I'd like to only dial this address from the stub. The server looks like this: func main() { grpcServer :...
Why do I need to dial a different socket for each grpc service? You don't. You can create one grpc.ClientConn and pass it to multiple pb.New*Client() functions, and they will share the same connection(s). func main() { cc, err := grpc.Dial("localhost:6000", grpc.WithInsecure()) if err != nil { log.Fa...
gRPC
52,634,217
13
I'm trying to get a basic gRPC C# client and server working using the .Net bindings for the official grpc library (version 1.20). But every time my client calls fail to reach the server with this error: Grpc.Core.RpcException: Status(StatusCode=Unknown, Detail="Stream removed") The failure is immediate (there is no wa...
Similar to Matěj Zábský I was struggling with "Stream removed" error and failed to get my BloomRPC to call my code. My circumstances were slightly different - my server portion was written with new Grpc.AspNetCore NuGet package in .NET Core 3, where as client was using a Grpc.Core Nuget package (that is compatible with...
gRPC
55,747,287
13
I want to define a request message in gRPC which should have a Json Object as a field For e.g. message UserRequest{ string name = 1; string city = 2; string email = 3; metainfo = 4;//A Json Object variable which can have any number of elements } How do I represent the metainfo property within proto def...
I think you want a .google.protobuf.Struct, via struct.proto - this essentially encapsulates a map<string, Value> fields, and is broadly akin to what you would want to describe via JSON. Additionally, Struct has custom JSON handling, as mentioned in the file: The JSON representation for Struct is JSON object. So: ...
gRPC
59,561,572
13
This is my first gRPC application. I'm attempting to invoke a server-streaming RPC call from a .NET 5 gRPC client (Grpc.Net.Client 2.35.0) which results in the following exception in my local development environment: Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestExc...
After further investigation, this appears related to proxy settings on my machine related to my company's network setup. Specifically, I have the following environment variables defined: http_proxy https_proxy .NET populates the HttpClient DefaultProxy from these environment variables. My company proxy appears to be ...
gRPC
66,500,195
13
I'm using sbt assembly to create a fat jar which can run on spark. Have dependencies on grpc-netty. Guava version on spark is older than the one required by grpc-netty and I run into this error: java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument. I was able to resolve this by setting userCl...
You are almost there. What shadeRule does is it renames class names, not library names: The main ShadeRule.rename rule is used to rename classes. All references to the renamed classes will also be updated. In fact, in com.google.guava:guava there are no classes with package com.google.guava: $ jar tf ~/Downloads/guav...
gRPC
45,989,052
12
I am using protobuf and grpc as interface between a client and server. The server is written in C and the client uses python to communicate to the server. I have a message created in protobuf like below. message value_obj { uint32 code = 1; uint32 value = 2; } message list_of_maps { map<uint32, value_o...
You can try using python dictionary for that: map1 = {} obj1 = value_obj() map1[1] = obj1 map2 = {} listOfMaps = list_of_maps(mapObj1=map1, mapObj2=map2)
gRPC
48,293,883
12
I have a grpc server and client that works as expected most of the time, but do get a "transport is closing" error occasionally: rpc error: code = Unavailable desc = transport is closing I'm wondering if it's a problem with my setup. The client is pretty basic connection, err := grpc.Dial(address, grpc.WithInsecure(),...
After much search, I have finally come to an acceptable and logical solution to this problem. The root-cause is this: The underlying TCP connection is closed abruptly, but neither the gRPC Client nor Server are 'notified' of this event. The challenge is at multiple levels: Kernel's management of TCP sockets Any interm...
gRPC
52,993,259
12
I'm writing gRPC services using ASP.NET Core using GRPC.ASPNETCore. I've tried to add an Exception Filter for gRPC methods like this services.AddMvc(options => { options.Filters.Add(typeof(BaseExceptionFilter)); }); or using the UseExceptionHandler extension method like this app.UseExceptionHandler(configure => { ...
Add custom interceptor in Startup services.AddGrpc(options => { { options.Interceptors.Add<ServerLoggerInterceptor>(); options.EnableDetailedErrors = true; } }); Create custom class. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Grpc.Core...
gRPC
58,277,184
12
I am trying to understand the grpc c++ async model flow. This article (link ) already explains many of my doubts. Here is the code for grpc_asycn_server. To understand when CompletionQueue is getting requests, I added a few print statements as follows: First inside the HandleRpcs() function. void HandleRpcs() { //...
The completion queue (cq_) structure handles several types of events, including both request and response events. The first call to proceed() enters the PROCESS stage of the state machine for the CallData object. During this stage: 1. A new CallData object is created; this inserts a request event into cq_ as you mentio...
gRPC
58,499,145
12
I've created 3 proto files and would like to keep it in a git repo: separated from all others files. The repository contains only .proto files. I have 3 microservices and each of them has their own repository that is using those proto files to communicate with each others: You can see on the picture above, that proto...
Here's what I suggest: Store your protos (and their go generating makefiles) in a single git repo. Each definition should be in their own directory for import simplicity tag the repo with a version - especially on potentially breaking changes import a particular proto defs from your micro-services e.g. import "github....
gRPC
60,464,363
12
How will I convert this datetime from the date? From this: 2016-02-29 12:24:26 to: Feb 29, 2016 So far, this is my code and it returns a nil value: let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy" dateFormatter.timeZone = NSTimeZone(name: "UTC") let date: NSDate? = dateFormatter.dateFromS...
This may be useful for who want to use dateformatter.dateformat; if you want 12.09.18 you use dateformatter.dateformat = "dd.MM.yy" Wednesday, Sep 12, 2018 --> EEEE, MMM d, yyyy 09/12/2018 --> MM/dd/yyyy 09-12-2018 14:11 --> MM-dd-yyyy HH:mm Sep 12, 2:11 PM ...
Swift
35,700,281
313
I'm really struggling with trying to read a JSON file into Swift so I can play around with it. I've spent the best part of 2 days re-searching and trying different methods but no luck as of yet so I have signed up to StackOverFlow to see if anyone can point me in the right direction..... My JSON file is called test.jso...
Follow the below code : if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") { if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil) { if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingO...
Swift
24,410,881
311
I am currently testing my app with Xcode 6 (Beta 6). UIActivityViewController works fine with iPhone devices and simulators but crashes with iPad simulators and devices (iOS 8) with following logs Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (<_UIAlertContro...
On iPad the activity view controller will be displayed as a popover using the new UIPopoverPresentationController, it requires that you specify an anchor point for the presentation of the popover using one of the three following properties: barButtonItem sourceView sourceRect In order to specify the anchor point you ...
Swift
25,644,054
308
I have a UITextField that I want to enlarge its width when tapped on. I set up the constraints and made sure the constraint on the left has the lower priority then the one that I am trying to animate on the right side. Here is the code that I am trying to use. // move the input box UIView.animateWithDuration(10.5, anim...
You need to first change the constraint and then animate the update. This should be in the superview. self.nameInputConstraint.constant = 8 Swift 2 UIView.animateWithDuration(0.5) { self.view.layoutIfNeeded() } Swift 3, 4, 5 UIView.animate(withDuration: 0.5) { self.view.layoutIfNeeded() }
Swift
25,649,926
306
I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double? In Objective-C, I can do like this: double myDouble = [myString doubleValue]; But how can I achieve this in Swift language?
Swift 2 Update There are new failable initializers that allow you to do this in more idiomatic and safe way (as many answers have noted, NSString's double value is not very safe because it returns 0 for non number values. This means that the doubleValue of "foo" and "0" are the same.) let myDouble = Double(myString) T...
Swift
24,031,621
305
What is the easiest (best) way to find the sum of an array of integers in swift? I have an array called multiples and I would like to know the sum of the multiples.
This is the easiest/shortest method I can find. Swift 3 and Swift 4: let multiples = [...] let sum = multiples.reduce(0, +) print("Sum of Array is : ", sum) Swift 2: let multiples = [...] sum = multiples.reduce(0, combine: +) Some more info: This uses Array's reduce method (documentation here), which allows you to "...
Swift
24,795,130
303
When trying to understand a program, or in some corner-cases, it's useful to find out what type something is. I know the debugger can show you some type information, and you can usually rely on type inference to get away with not specifying the type in those situations, but still, I'd really like to have something like...
Swift 3 version: type(of: yourObject)
Swift
24,101,450
303
label.font.pointSize is read-only, so I'm not sure how to change it.
You can do it like this: label.font = UIFont(name: label.font.fontName, size: 20) Or like this: label.font = label.font.withSize(20) This will use the same font. 20 can be whatever size you want of course. Note: The latter option will overwrite the current font weight to regular so if you want to preserve the font we...
Swift
24,356,888
301
How can I remove last character from String variable using Swift? Can't find it in documentation. Here is full example: var expression = "45+22" expression = expression.substringToIndex(countElements(expression) - 1)
Swift 4.0 (also Swift 5.0) var str = "Hello, World" // "Hello, World" str.dropLast() // "Hello, Worl" (non-modifying) str // "Hello, World" String(str.dropLast()) // "Hello, Worl" st...
Swift
24,122,288
301
I am working on a money input screen and I need to implement a custom init to set a state variable based on the initialized amount. I thought the following would work: struct AmountView : View { @Binding var amount: Double @State var includeDecimal = false init(amount: Binding<Double>) { self.a...
Argh! You were so close. This is how you do it. You missed a dollar sign (beta 3) or underscore (beta 4), and either self in front of your amount property, or .value after the amount parameter. All these options work: You'll see that I removed the @State in includeDecimal, check the explanation at the end. This is usin...
Swift
56,973,959
299
As the question states, I would mainly like to know whether or not my code is running in the simulator, but would also be interested in knowing the specific iphone version that is running or being simulated. EDIT: I added the word 'programmatically' to the question name. The point of my question is to be able to dynami...
Already asked, but with a very different title. What #defines are set up by Xcode when compiling for iPhone I'll repeat my answer from there: It's in the SDK docs under "Compiling source code conditionally" The relevant definition is TARGET_OS_SIMULATOR, which is defined in /usr/include/TargetConditionals.h within the ...
Swift
458,304
296
I have a design that implements a dark blue UITextField, as the placeholder text is by default a dark grey colour I can barely make out what the place holder text says. I've googled the problem of course but I have yet to come up with a solution while using the Swift language and not Obj-c. Is there a way to change the...
You can set the placeholder text using an attributed string. Just pass the color you want to the attributes parameter. Swift 5: let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30)) myTextField.backgroundColor = .blue myTextField.attributedPlaceholder = NSAttributedString( string: "Placeh...
Swift
26,076,054
295
How can I convert NSRange to Range<String.Index> in Swift? I want to use the following UITextFieldDelegate method: func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { textField.text.stringByReplacingCharactersInRange(??...
As of Swift 4 (Xcode 9), the Swift standard library provides methods to convert between Swift string ranges (Range<String.Index>) and NSString ranges (NSRange). Example: let str = "a👿b🇩🇪c" let r1 = str.range(of: "🇩🇪")! // String range to NSRange: let n1 = NSRange(r1, in: str) print((str as NSString).substring(wi...
Swift
25,138,339
295
How could I split a string over multiple lines such as below? var text:String = "This is some text over multiple lines"
Swift 4 includes support for multi-line string literals. In addition to newlines they can also contain unescaped quotes. var text = """ This is some text over multiple lines """ Older versions of Swift don't allow you to have a single literal over multiple lines but you can add literals together over multi...
Swift
24,091,233
295
Whenever I try to run my app in Xcode 6 Beta 4 I am getting the error: The file "MyApp.app" couldn't be opened because you don't have permission to view it. This error appears no matter what simulator or device I target. I have tried: Deleting all Derived Data from Organizer in Xcode Repairing permissions on my drive...
I use Xcode6 GM. I encountered the same problem. What I did was to go to Build Settings -> Build Options. Then I changed the value of the "Compiler for C/C++/Objective-C" to Default Compiler.
Swift
24,924,809
294
I am trying to run the code below: import UIKit class LoginViewController: UIViewController { @IBOutlet var username : UITextField = UITextField() @IBOutlet var password : UITextField = UITextField() @IBAction func loginButton(sender : AnyObject) { if username .isEqual("") || password.isEqual("")) { ...
With Swift you don't need anymore to check the equality with isEqualToString You can now use == Example: let x = "hello" let y = "hello" let isEqual = (x == y) now isEqual is true.
Swift
24,096,708
293
I tried var timer = NSTimer() timer(timeInterval: 0.01, target: self, selector: update, userInfo: nil, repeats: false) But, I got an error saying '(timeInterval: $T1, target: ViewController, selector: () -> (), userInfo: NilType, repeats: Bool) -> $T6' is not identical to 'NSTimer'
This will work: override func viewDidLoad() { super.viewDidLoad() // Swift block syntax (iOS 10+) let timer = Timer(timeInterval: 0.4, repeats: true) { _ in print("Done!") } // Swift >=3 selector syntax let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.updat...
Swift
24,007,518
293
In Objective-C instance data can be public, protected or private. For example: @interface Foo : NSObject { @public int x; @protected: int y; @private: int z; } -(int) apple; -(int) pear; -(int) banana; @end I haven't found any mention of access modifiers in the Swift reference. Is it possible to li...
As of Swift 3.0.1, there are 4 levels of access, described below from the highest (least restrictive) to the lowest (most restrictive). 1. open and public Enable an entity to be used outside the defining module (target). You typically use open or public access when specifying the public interface to a framework. Howev...
Swift
24,003,918
293
In Swift you can check the class type of an object using 'is'. How can I incorporate this into a 'switch' block? I think it's not possible, so I'm wondering what is the best way around this.
You absolutely can use is in a switch block. See "Type Casting for Any and AnyObject" in the Swift Programming Language (though it's not limited to Any of course). They have an extensive example: for thing in things { switch thing { case 0 as Int: println("zero as an Int") case 0 as Double: ...
Swift
25,724,527
291
I am trying to change the font of a UIButton using Swift... myButton.font = UIFont(name: "...", 10) However .font is deprecated and I'm not sure how to change the font otherwise. Any suggestions?
Use titleLabel instead. The font property is deprecated in iOS 3.0. It also does not work in Objective-C. titleLabel is label used for showing title on UIButton. myButton.titleLabel?.font = UIFont(name: YourfontName, size: 20) However, while setting title text you should only use setTitle:forControlState:. Do not use...
Swift
25,002,017
291
I am a little confused on the answer that Xcode is giving me to this experiment in the Swift Programming Language Guide: // Use a for-in to iterate through a dictionary (experiment) let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25] ] var ...
Dictionaries in Swift (and other languages) are not ordered. When you iterate through the dictionary, there's no guarantee that the order will match the initialization order. In this example, Swift processes the "Square" key before the others. You can see this by adding a print statement to the loop. 25 is the 5th elem...
Swift
24,111,627
291
I have an app that runs on the iPhone and iPod Touch, it can run on the Retina iPad and everything but there needs to be one adjustment. I need to detect if the current device is an iPad. What code can I use to detect if the user is using an iPad in my UIViewController and then change something accordingly?
There are quite a few ways to check if a device is an iPad. This is my favorite way to check whether the device is in fact an iPad: if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) { return YES; /* Device is iPad */ } The way I use it #define IDIOM UI_USER_INTERFACE_IDIOM() #define IPAD UIUserInt...
Swift
10,167,221
290
I have a simple Dictionary which is defined like: var dict : NSDictionary = [ 1 : "abc", 2 : "cde"] Now I want to add an element into this dictionary: 3 : "efg" How can I append 3 : "efg" into this existing dictionary?
You're using NSDictionary. Unless you explicitly need it to be that type for some reason, I recommend using a Swift dictionary. You can pass a Swift dictionary to any function expecting NSDictionary without any extra work, because Dictionary<> and NSDictionary seamlessly bridge to each other. The advantage of the nativ...
Swift
27,313,242
289
How can I generate a random alphanumeric string in Swift?
Swift 4.2 Update Swift 4.2 introduced major improvements in dealing with random values and elements. You can read more about those improvements here. Here is the method reduced to a few lines: func randomString(length: Int) -> String { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" r...
Swift
26,845,307
289
I am trying to make an autocorrect system, and when a user types a word with a capital letter, the autocorrect doesn't work. In order to fix this, I made a copy of the string typed, applied .lowercaseString, and then compared them. If the string is indeed mistyped, it should correct the word. However then the word that...
Including mutating and non mutating versions that are consistent with API guidelines. Swift 3: extension String { func capitalizingFirstLetter() -> String { let first = String(characters.prefix(1)).capitalized let other = String(characters.dropFirst()) return first + other } mutatin...
Swift
26,306,326
287
From Apple's documentation: You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as opt...
An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type: var name: String? = "Bertie" Optionals (along with Generics) are one of the most difficult Swift concepts to understand. Because of how they are written and used, it's easy to get a wrong idea o...
Swift
24,003,642
287
What would be the most proper way to get both top and bottom height for the unsafe areas?
Try this : In Objective C if (@available(iOS 11.0, *)) { UIWindow *window = UIApplication.sharedApplication.windows.firstObject; CGFloat topPadding = window.safeAreaInsets.top; CGFloat bottomPadding = window.safeAreaInsets.bottom; } In Swift if #available(iOS 11.0, *) { let window = UIApplication.share...
Swift
46,829,840
285
I'm trying to check system information in Swift. I figured out, that it could be achieved by code: var sysData:CMutablePointer<utsname> = nil let retVal:CInt = uname(sysData) I have two problems with this code: What should be sysData's initial value? This example gives -1 in retVal probably because sysData is nil. Ho...
For iOS, try: var systemVersion = UIDevice.current.systemVersion For OS X, try: var systemVersion = NSProcessInfo.processInfo().operatingSystemVersion If you just want to check if the users is running at least a specific version, you can also use the following Swift 2 feature which works on iOS and OS X: if #ava...
Swift
24,503,001
284
I have a large image in Assets.xcassets. How to resize this image with SwiftUI to make it small? I tried to set frame but it doesn't work: Image(room.thumbnailImage) .frame(width: 32.0, height: 32.0)
You should use .resizable() before applying any size modifications on an Image. Image(room.thumbnailImage) .resizable() .frame(width: 32.0, height: 32.0)
Swift
56,505,692
282
I got an error on Xcode saying that there was no information about the view controller. Could not insert new outlet connection: Could not find any information for the class named Why is this happening?
Here are some things that can fix this (in increasing order of difficulty): Clean the project (Product > Clean) Manually paste in @IBOutlet weak var viewName: UIView! // or @IBAction func viewTapped(_ sender: Any) { } and control drag to it. (Change type as needed.) Also see this. Completely close Xcode and restart y...
Swift
29,923,881
281
I would like to use Swift code to properly position items in my app for no matter what the screen size is. For example, if I want a button to be 75% of the screen wide, I could do something like (screenWidth * .75) to be the width of the button. I have found that this could be determined in Objective-C by doing CGFloat...
In Swift 5.0 let screenSize: CGRect = UIScreen.main.bounds Pay attention that UIScreen.main will be deprecated in future version of iOS. So we can use view.window.windowScene.screen. Swift 4.0 // Screen width. public var screenWidth: CGFloat { return UIScreen.main.bounds.width } // Screen height. public var scree...
Swift
24,110,762
281
Simple question here. I have a UIButton, currencySelector, and I want to programmatically change the text. Here's what I have: currencySelector.text = "foobar" Xcode gives me the error "Expected Declaration". What am I doing wrong, and how can I make the button's text change?
In Swift 3, 4, 5: button.setTitle("Button Title", for: .normal) Otherwise: button.setTitle("Button Title", forState: UIControlState.Normal) Also an @IBOutlet has to declared for the button.
Swift
26,326,296
279
Given this code: import SwiftUI struct ContentView: View { var body: some View { VStack(alignment: .leading) { Text("Title") .font(.title) Text("Content") .lineLimit(nil) .font(.body) Spacer() } .background(Color.red) } } #if DEBUG struct ContentView_Preview...
Try using the .frame modifier with the following options: .frame( minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading ) struct ContentView: View { var body: some View { VStack(alignment: .leading) { Text("Hello World") .font...
Swift
56,487,323
278
Question Apple's docs specify that: willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context. Is it possible to force these to be called during initialization? Why? Let's say I have this class class S...
If you use defer inside of an initializer, for updating any optional properties or further updating non-optional properties that you've already initialized and after you've called any super.init() methods, then your willSet, didSet, etc. will be called. I find this to be more convenient than implementing separate meth...
Swift
25,230,780
277
I'm building an app using swift in the latest version of Xcode 6, and would like to know how I can modify my button so that it can have a rounded border that I could adjust myself if needed. Once that's done, how can I change the color of the border itself without adding a background to it? In other words I want a slig...
Use button.layer.cornerRadius, button.layer.borderColor and button.layer.borderWidth. Note that borderColor requires a CGColor, so you could say (Swift 3/4): button.backgroundColor = .clear button.layer.cornerRadius = 5 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.black.cgColor
Swift
26,961,274
275
I have not yet been able to figure out how to get a substring of a String in Swift: var str = “Hello, playground” func test(str: String) -> String { return str.substringWithRange( /* What goes here? */ ) } test (str) I'm not able to create a Range in Swift. Autocomplete in the Playground isn’t super helpful - this is...
You can use the substringWithRange method. It takes a start and end String.Index. var str = "Hello, playground" str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground" To change the start and end index, use advancedBy(n). var str = "Hello, playground" str.substringWi...
Swift
24,044,851
274
Does anyone know how to convert a UIImage to a Base64 string, and then reverse it? I have the below code; the original image before encoding is good, but I only get a blank image after I encode and decode it. NSData *imageData = UIImagePNGRepresentation(viewImage); NSString *b64EncStr = [self encode: imageData]; NSSt...
Swift First we need to have image's NSData //Use image name from bundle to create NSData let image : UIImage = UIImage(named:"imageNameHere")! //Now use image to create into NSData format let imageData:NSData = UIImagePNGRepresentation(image)! //OR next possibility //Use image's path to create NSData let url:NSURL = ...
Swift
11,251,340
273
I've searched the Swift book, but can't find the Swift version of @synchronized. How do I do mutual exclusion in Swift?
You can use GCD. It is a little more verbose than @synchronized, but works as a replacement: let serialQueue = DispatchQueue(label: "com.test.mySerialQueue") serialQueue.sync { // code }
Swift
24,045,895
271
How do you add an in-app purchase to an iOS app? What are all the details and is there any sample code? This is meant to be a catch-all of sorts for how to add in-app purchases to iOS apps
Swift Users Swift users can check out My Swift Answer for this question.Or, check out Yedidya Reiss's Answer, which translates this Objective-C code to Swift. Objective-C Users The rest of this answer is written in Objective-C App Store Connect Go to appstoreconnect.apple.com and log in Click My Apps then click the ap...
Swift
19,556,336
270
How do I programmatically set the InitialViewController for a Storyboard? I want to open my storyboard to a different view depending on some condition which may vary from launch to launch.
How to without a dummy initial view controller Ensure all initial view controllers have a Storyboard ID. In the storyboard, uncheck the "Is initial View Controller" attribute from the first view controller. If you run your app at this point you'll read: Failed to instantiate the default view controller for UIMainStory...
Swift
10,428,629
268
In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects? The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with filter, map or reduce?
By far the neatest way to get the first N elements of a Swift array is using prefix(_ maxLength: Int): let array = [1, 2, 3, 4, 5, 6, 7] let slice5 = array.prefix(5) // ArraySlice let array5 = Array(slice5) // [1, 2, 3, 4, 5] the one-liner is: let first5 = Array(array.prefix(5)) This has the benefit of being bounds...
Swift
28,527,797
267
I need to execute an action (emptying an array), when the back button of a UINavigationController is pressed, while the button still causes the previous ViewController on the stack to appear. How could I accomplish this using swift?
Replacing the button to a custom one as suggested on another answer is possibly not a great idea as you will lose the default behavior and style. One other option you have is to implement the viewWillDisappear method on the View Controller and check for a property named isMovingFromParentViewController. If that propert...
Swift
27,713,747
267
So now with swift, the ReactiveCocoa people have rewritten it in version 3.0 for swift Also, there's been another project spun up called RxSwift. I wonder if people could add information about what the differences in design/api/philosophy of the two frameworks are (please, in the spirit of SO, stick to things which are...
This is a very good question. Comparing the two worlds is very hard. Rx is a port of what Reactive Extensions are in other languages like C#, Java or JS. Reactive Cocoa was inspired by Functional Reactive Programming, but in the last months, has been also pointed as inspired by Reactive Extensions as well. The outcome ...
Swift
32,542,846
265
I'm looking for a clean example of how to copy text to iOS clipboard that can then be used/pasted in other apps. The benefit of this function is that the text can be copied quickly, without the standard text highlighting functions of the traditional text copying. I am assuming that the key classes are in UIPasteboard, ...
If all you want is plain text, you can just use the string property. It's both readable and writable: // write to clipboard UIPasteboard.general.string = "Hello world" // read from clipboard let content = UIPasteboard.general.string (When reading from the clipboard, the UIPasteboard documentation also suggests you mi...
Swift
24,670,290
265
Swift has: Strong References Weak References Unowned References How is an unowned reference different from a weak reference? When is it safe to use an unowned reference? Are unowned references a security risk like dangling pointers in C/C++?
Both weak and unowned references do not create a strong hold on the referred object (a.k.a. they don't increase the retain count in order to prevent ARC from deallocating the referred object). But why two keywords? This distinction has to do with the fact that Optional types are built-in the Swift language. Long story ...
Swift
24,011,575
265
How do I convert, NSDate to NSString so that only the year in @"yyyy" format is output to the string?
How about... NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy"]; //Optionally for time zone conversions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance]; //unless ARC is active [formatter r...
Swift
576,265
265
I have lots of code in Swift 2.x (or even 1.x) projects that looks like this: // Move to a background thread to do some long running work dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let image = self.loadOrGenerateAnImage() // Bounce back to the main thread to update the UI ...
Since the beginning, Swift has provided some facilities for making ObjC and C more Swifty, adding more with each version. Now, in Swift 3, the new "import as member" feature lets frameworks with certain styles of C API -- where you have a data type that works sort of like a class, and a bunch of global functions to wor...
Swift
37,801,370
263
I send the user over to a page on a button click. This page is a UITableViewController. Now if the user taps on a cell, I would like to push him back to the previous page. I thought about something like self.performSegue("back").... but this seems to be a bad idea. What is the correct way to do it?
Swift 3: If you want to go back to the previous view controller _ = navigationController?.popViewController(animated: true) If you want to go back to the root view controller _ = navigationController?.popToRootViewController(animated: true) If you are not using a navigation controller then pls use the below code. sel...
Swift
28,760,541
263
I am trying to get the difference between the current date as NSDate() and a date from a PHP time(); call for example: NSDate(timeIntervalSinceReferenceDate: 1417147270). How do I go about getting the difference in time between the two dates. I'd like to have a function that compares the two dates and if(seconds > 60) ...
Xcode 8.3 • Swift 3.1 or later You can use Calendar to help you create an extension to do your date calculations as follow: extension Date { /// Returns the amount of years from another date func years(from date: Date) -> Int { return Calendar.current.dateComponents([.year], from: date, to: self).year ?...
Swift
27,182,023
262
Can anyone tell me how I can mimic the bottom sheet in the new Apple Maps app in iOS 10? In Android, you can use a BottomSheet which mimics this behaviour, but I could not find anything like that for iOS. Is that a simple scroll view with a content inset, so that the search bar is at the bottom? I am fairly new to iOS ...
I don't know how exactly the bottom sheet of the new Maps app, responds to user interactions. But you can create a custom view that looks like the one in the screenshots and add it to the main view. I assume you know how to: 1- create view controllers either by storyboards or using xib files. 2- use googleMaps or Apple...
Swift
37,967,555
258
I want to do something in Swift that I'm used to doing in multiple other languages: throw a runtime exception with a custom message. For example (in Java): throw new RuntimeException("A custom message here") I understand that I can throw enum types that conform to the ErrorType protocol, but I don't want to have to ...
The simplest approach is probably to define one custom enum with just one case that has a String attached to it: enum MyError: Error { case runtimeError(String) } Example usage would be something like: func someFunction() throws { throw MyError.runtimeError("some message") } do { try someFunction() } catch...
Swift
31,443,645
258
I would like to play a sound using Swift. My code worked in Swift 1.0 but now it doesn't work anymore in Swift 2 or newer. override func viewDidLoad() { super.viewDidLoad() let url:NSURL = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOfURL...
Most preferably you might want to use AVFoundation. It provides all the essentials for working with audiovisual media. Update: Compatible with Swift 2, Swift 3 and Swift 4 as suggested by some of you in the comments. Swift 2.3 import AVFoundation var player: AVAudioPlayer? func playSound() { let url = NSBundl...
Swift
32,036,146
257
I want to make one function in my swift project that converts String to Dictionary json format but I got one error: Cannot convert expression's type (@lvalue NSData,options:IntegerLitralConvertible ... This is my code: func convertStringToDictionary (text:String) -> Dictionary<String,String> { var data :NSData =...
Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all. Swift 3 func convertToDictionary(text: String) -> [String: Any]? { i...
Swift
30,480,672
257
An NSSet can be converted to Array using set.allObjects() but there is no such method in the new Set (introduced with Swift 1.2). It can still be done by converting Swift Set to NSSet and use the allObjects() method but that is not optimal.
You can create an array with all elements from a given Swift Set simply with let array = Array(someSet) This works because Set conforms to the SequenceType protocol and an Array can be initialized with a sequence. Example: let mySet = Set(["a", "b", "a"]) // Set<String> let myArray = Array(mySet) // Array<Str...
Swift
29,046,695
256
Many languages support documentation comments to allow a generator (like javadoc or doxygen) to generate code documentation by parsing that same code. Does Swift have any type documentation comment feature like this?
Documentation comments are supported natively in Xcode, producing smartly rendered documentation in Quick Help (both in the popover when ⌥-clicking symbols, and in the Quick Help Inspector ⌥⌘2). Symbol documentation comments are now based on the same Markdown syntax used by rich playground comments, so a lot of what yo...
Swift
24,047,991
255