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 = "domain";
import "google/protobuf/timestamp.proto";
message Foo {
Timestamp modifiedTime = 1;
...
}
I'm seeing the following errors:
domain.proto: Import "google/protobuf/timestamp.proto" was not found or had errors.
domain.proto:44:5: "Timestamp" is not defined.
Am I missing something, or this is not yet supported?
| 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.protobuf.Timestamp modifiedTime = 1;
...
}
| 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.health_ping)
if health.message == u'PONG':
return {
u'healthy': True,
u'message': {
u'healthy': True,
u'message': u'success'
},
u'status_code': 200
}
except Exception as e:
if str(e.code()) == u'StatusCode.UNAVAILABLE':
return {
u'healthy': False,
u'message': {
u'healthy': False,
u'message': (u'[503 Unavailable] connection to worker '
u'failed')},
u'status_code': 200}
elif str(e.code()) == u'StatusCode.INTERNAL':
return {
u'healthy': False,
u'message': {
u'healthy': False,
u'message': (u'[500 Internal] worker encountered '
u'an error while responding')},
u'status_code': 200}
return {
u'healthy': False,
u'message': {u'healthy': False, u'message': e.message},
u'status_code': 500
}
the client is a stub:
channel = grpc.insecure_channel(address)
stub = WorkerStub(channel)
return stub
the proto is:
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.company.project.worker";
option java_outer_classname = "ProjectWorker";
option objc_class_prefix = "PJW";
package projectworker;
service Worker {
rpc Health (Ping) returns (Pong) {}
}
// The request message containing PONG
message Ping {
string message = 1;
}
// The response message containing PONG
message Pong {
string message = 1;
}
Using this code, how would I then add a timeout to ensure that I can always respond rather than fail and hang?
| 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 the pros and cons of these two options?
idleTimeout
Set the duration without ongoing RPCs before going to idle mode. In
idle mode the channel shuts down all connections, the NameResolver and
the LoadBalancer. A new RPC would take the channel out of idle mode. A
channel starts in idle mode. Defaults to 30 minutes.
This is an advisory option. Do not rely on any specific behavior
related to this option.
keepAliveWithoutCalls
Sets whether keepalive will be performed when there are no outstanding
RPC on a connection. Defaults to false.
Clients must receive permission from the service owner before enabling
this option. Keepalives on unused connections can easilly accidentally
consume a considerable amount of bandwidth and CPU. idleTimeout()
should generally be used instead of this option.
| 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 used when you are willing to spend client, server, and network resources to have lower latency for very infrequent RPCs.
| 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 difference right?
| 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 code that accepts regular JavaScript objects.
The static code generation (using protoc) requires the user to create protobuf objects, which means that input validation will be done earlier. It is also a workflow that is more consistent with other languages.
| 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 if a client is meant to create multiple stub instances sharing the channel or share a single stub. Please clarify the conceptual relationship between stubs, channels, and unique client connections.
Diving a little deeper:
A server can serve more than one service and a client endpoint can use a single channel to connect corresponding stub types to each of those services. For that purpose, it is clear the different stub types share the single channel to talk to the server endpoint. Does gRPC expect only one client per channel for a given service or can I have multiple clients on the client endpoint talking to a single service? If allowed, how do I achieve multiple clients for a given service on a client endpoint? How does the server distinguish these as independent clients?
As an aside, This SO post indicates both Channels and Stubs are thread-safe. (The post is specifically for Java, but I'm assuming it carries over to C++).
| 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 object known as stub (for some languages, the preferred term is client) that implements the same methods as the service.
Conclude : A stub represents a single client.
From reading many other materials, I'm sure that a single channel(tcp connection) can be multiplexed, and now we get two options to achieve it:
one channel <--> one stub
one stub <--> multiple streams
one channel <--> multiple stubs
one stub <--> multiple streams
the only difference is that whether to share a channel among the stubs or not. My answer is: Yes, you can, for the reasons:
your reports of people having issues example is written in ruby, but I can also find python examples standing on the opposite side. So the behavior may depends on language implementations.
the synchronous cpp client examples use one stub object to issue a rpc, and it doesn't have any stream objects associated with, then the only way for multiplexing purpose is just share one single channel object among the stubs.
Combining the above two reasons, I conclude that: sharing a channel among the stubs is valid in C++.
Now, back to you questions:
Does gRPC expect only one client per channel for a given service or can I have multiple clients on the client endpoint talking to a single service?
Sure, you can have multiple clients talking to a single service.
If allowed, how do I achieve multiple clients for a given service on a client endpoint?
You can just have multiple stubs generated either from one single channel or from multiple channels, former is a better choice for connection overhead considerations.
How does the server distinguish these as independent clients?
This is due to http2, it can be multiplexed and has its own rules to achieve this, what grpc need to do is just follow thoes rules.
Hope this helps!
| 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 client can cancel the call:
Context.CancellableContext cancellableContext =
Context.current().withCancellation();
cancellableContext.run(() -> {
stub.subscribe(request, callback);
});
// do other stuff / wait for reason to unsubscribe
cancellableContext.cancel(new InterruptedException());
However, the server does not seem to notice that a client has cancelled its call. I'm testing this with a dummy server implementation:
@Override
public void subscribe(SubscribeRequest request,
StreamObserver<SubscribeResponse> responseObserver) {
// in real code, this will happen in a separate thread.
while (!Thread.interrupted()) {
responseObserver.onNext(SubscribeResponse.getDefaultInstance());
}
}
The server will happily continue sending its messages into the ether. How can the server recognize that the call was cancelled by the client and thus stop sending responses?
| 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
}
This, to me, begs the question why subscribe isn't passed a ServerCallStreamObserver to begin with.
| 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)
at Object.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener.Object.<anonymous>.InterceptingListener._callNext (node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.Object.<anonymous>.InterceptingListener.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:618:8)
at callback (node_modules/grpc/src/client_interceptors.js:847:24)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 skipped, 2 total
Snapshots: 0 total
Time: 106.03s, estimated 116s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
owner@G700:~/PhpstormProjects/shopify/bu
FAIL functions/src/classes/__tests__/FirestoreConnection.test.ts (108.991s)
✕ creates new record (100029ms)
○ skipped
● creates new record
: Timeout - Async callback was not invoked within the 100000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 100000ms timeout specified by jest.setTimeout.Error:
51 |
52 |
> 53 | test("creates new record", async () => {
| ^
54 | const addedDocument = await db
55 | .createNew(RecordTypes.globalRule, {
56 | storeId : "dummyStoreId"
at new Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
at Object.<anonymous> (functions/src/classes/__tests__/FirestoreConnection.test.ts:53:1)
● creates new record
14 UNAVAILABLE: failed to connect to all addresses
at Object.<anonymous>.exports.createStatusError (node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener.Object.<anonymous>.InterceptingListener._callNext (node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.Object.<anonymous>.InterceptingListener.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:618:8)
at callback (node_modules/grpc/src/client_interceptors.js:847:24)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 skipped, 2 total
Snapshots: 0 total
Time: 111.16s
Ran all test suites related to changed files.
// FirebaseConnection.ts, inside the class
protected async addDocument(collectionName: string, documentData: object): Promise<firestore.DocumentSnapshot|null> {
try {
const newlyAddedDocument = await this.database
.collection(collectionName)
.add(documentData);
return await newlyAddedDocument.get();
}
catch (e) {
console.log(e, `=====error=====`);
return null;
}
}
// --------------- Public Methods
public async createNew(type: RecordTypes, documentData: object): Promise<firestore.DocumentSnapshot|null> {
this.verifySchemaIsCorrect(type, documentData);
const collectionName = this.getCollectionName(type);
return await this.addDocument(collectionName, documentData);
}
// FirebaseConnection.test.ts
import * as firebaseTesting from "@firebase/testing";
import {RecordTypes} from "../../../../shared";
import FirestoreConnection from "../FirestoreConnection";
/* * * * * * * * * * * * * * * * * * * * *
Setup
* * * * * * * * * * * * * * * * * * * * */
const createTestDatabase = (credentials): any => {
return firebaseTesting
.initializeTestApp({
projectId: 'testProject',
auth: credentials
})
.firestore();
};
const nullAllApps = firebaseTesting
.apps().map(app => app.delete());
const db = new FirestoreConnection('testShopDomain', createTestDatabase(null));
/* * * * * * * * * * * * * * * * * * * * *
Tests
* * * * * * * * * * * * * * * * * * * * */
test("creates new record", async () => {
const addedDocument = await db
.createNew(RecordTypes.globalRule, {
storeId : "dummyStoreId"
, globalPercent : 40
});
expect(addedDocument).toEqual({
storeId : "dummyStoreId"
, globalPercent : 40
, badProp : 0
});
}, 100000);
Is anyone able to tell why this is happening? Looking at the documentation this appears to be a lower level library: https://grpc.github.io/grpc/node/
Update
After it was suggested that the server/emulator was not found by gRPC, I ran firebase serve --only functions,firestore. Terminal showed emulators running on different ports for both services. Rerunning jest --watch now produces a slightly different error:
2 UNKNOWN:
at Object.<anonymous>.exports.createStatusError (node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener.Object.<anonymous>.InterceptingListener._callNext (node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.Object.<anonymous>.InterceptingListener.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:618:8)
at callback (node_modules/grpc/src/client_interceptors.js:847:24)
| 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 seems to be a popular choice for microservice internal communication because of its performance and efficiency.
However, gRPC makes it more difficult to query relational data and requires more work to hook up to our API gateway.
Option 2: GraphQL
Another option is for each microservice to implement their own GraphQL schema so they can be easily stitched together using Apollo Federation in the API gateway.
This approach will make queries more flexible, but internal requests become less performant because of the lack of protocol buffers.
Option 3: Both?
Perhaps another alternative is to use the best of both worlds by implementing mutations in gRPC and queries in GraphQL. Or just creating two APIs, one facing the gateway clients and one for communication between services.
Questions
How do we decide which approach to use?
Are there any significant (dis)advantages we should consider? E.g. in terms of ease of use, maintainability, scalability, performance, etc?
Are there better alternatives for this use case?
| 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 write model.
Use hexagonal architecture (we use Explicit Architecture in my company) to implement DDD - Domain-driven-design.
In order to seamlessly integrate Apollo, you will have to implement GraphQL layer into the architecture of all of your backend services.
In read model, implement GraphQL layer. You will benefit from the federation (parallel reads of data from several microservices will be "joined" in federation engine without any participation of your API nodes).
For communication among your backend services in write model (mutations), use gRPC.
gRPC will make it possible to call your CQRS commands remotly like it was local.
So, your remote microservices will look like part of your local backend code.
You will also need a message-broker like RabbitMQ or Kafka to manage some more complex state changes via events and message queues.
| 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 reconnection automatically, but I just cannot get it to work and I fear my implementation is incorrect in the first instance.
Calling code from main:
go func() {
if err := gRPCClient.ProcessRequests(); err != nil {
log.Error("Error while processing Requests")
//do something here??
}
}()
My code in the gRPCClient wrapper module:
func (grpcclient *gRPCClient) ProcessRequests() error {
defer grpcclient.Close()
for {
request, err := reqclient.stream.Recv()
log.Info("Request received")
if err == io.EOF {
break
}
if err != nil {
//when pod is recycled, this is what's hit with err:
//rpc error: code = Unavailable desc = transport is closing"
//what is the correct pattern for recovery here so that we can await connection
//and continue processing requests once more?
//should I return err here and somehow restart the ProcessRequests() go routine in the
//main funcition?
break
} else {
//the happy path
//code block to process any requests that are received
}
}
return nil
}
func (reqclient *RequestClient) Close() {
//this is called soon after the conneciton drops
reqclient.conn.Close()
}
EDIT:
Emin Laletovic answered my question elegantly below and gets it most of the way there.
I had to make a few changes to the waitUntilReady function:
func (grpcclient *gRPCClient) waitUntilReady() bool {
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second) //define how long you want to wait for connection to be restored before giving up
defer cancel()
currentState := grpcclient.conn.GetState()
stillConnecting := true
for currentState != connectivity.Ready && stillConnecting {
//will return true when state has changed from thisState, false if timeout
stillConnecting = grpcclient.conn.WaitForStateChange(ctx, currentState)
currentState = grpcclient.conn.GetState()
log.WithFields(log.Fields{"state: ": currentState, "timeout": timeoutDuration}).Info("Attempting reconnection. State has changed to:")
}
if stillConnecting == false {
log.Error("Connection attempt has timed out.")
return false
}
return true
}
| 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 connection is back up.
The pseudo-code for waiting the RPC connection to be in the READY state and establishing a new stream might look something like this:
func (grpcclient *gRPCClient) ProcessRequests() error {
defer grpcclient.Close()
go grpcclient.process()
for {
select {
case <- grpcclient.reconnect:
if !grpcclient.waitUntilReady() {
return errors.New("failed to establish a connection within the defined timeout")
}
go grpcclient.process()
case <- grpcclient.done:
return nil
}
}
}
func (grpcclient *gRPCClient) process() {
reqclient := GetStream() //always get a new stream
for {
request, err := reqclient.stream.Recv()
log.Info("Request received")
if err == io.EOF {
grpcclient.done <- true
return
}
if err != nil {
grpcclient.reconnect <- true
return
} else {
//the happy path
//code block to process any requests that are received
}
}
}
func (grpcclient *gRPCClient) waitUntilReady() bool {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) //define how long you want to wait for connection to be restored before giving up
defer cancel()
return grpcclient.conn.WaitForStateChange(ctx, conectivity.Ready)
}
EDIT:
Revisiting the code above, a couple of mistakes should be corrected. The WaitForStateChange function waits for the connection state to change from the passed state, it doesn't wait for the connection to change into the passed state.
It is better to track the current state of the connection and use the Connect function to connect if the channel is idle.
func (grpcclient *gRPCClient) ProcessRequests() error {
defer grpcclient.Close()
go grpcclient.process()
for {
select {
case <- grpcclient.reconnect:
if !grpcclient.isReconnected(1*time.Second, 60*time.Second) {
return errors.New("failed to establish a connection within the defined timeout")
}
go grpcclient.process()
case <- grpcclient.done:
return nil
}
}
}
func (grpcclient *gRPCClient) isReconnected(check, timeout time.Duration) bool {
ctx, cancel := context.context.WithTimeout(context.Background(), timeout)
defer cancel()
ticker := time.NewTicker(check)
for{
select {
case <- ticker.C:
grpcclient.conn.Connect()
if grpcclient.conn.GetState() == connectivity.Ready {
return true
}
case <- ctx.Done():
return false
}
}
}
| 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 to the batch processing, which means the size of the threadpool must be larger than 400 to avoid blocking.
Can this be done asynchronously?
Thanks a lot.
class EventReporting(ss_pb2.BetaEventReportingServicer, ss_pb2.BetaDeviceMgtServicer):
def ReportEvent(self, request, context):
res = tasks.add.delay(1,2)
result = res.get() ->here i have to block
return ss_pb2.GeneralReply(message='Hello, %s!' % result.message)
| 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 is a copy of the example server:
import logging
import asyncio
from grpc import aio
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
async def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
async def serve():
server = aio.server()
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
listen_addr = '[::]:50051'
server.add_insecure_port(listen_addr)
logging.info("Starting server on %s", listen_addr)
await server.start()
await server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.run(serve())
See my other answer for how to implement the client.
| 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 doesn't seem to be anything you can put inside the brackets. So, given that I can terminate the definition with ; what are that brackets for?
| 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 Generate(Request) returns (Response) {
option (google.api.http) = {
post: "/api/{Client}"
body: "*"
};
}
}
You can see full reference here cloud.google.com/service-management/reference
Note: I took the reference link from the grpc-gateway repo
| 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 the much better solution will be available to you.
| 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 error:
"Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read."
Now I could probably try to find a workaround for docker specifically, but this still doesn't feel right. Does anyone know of a good "production ready" way to keep the service running?
| 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 it is stopped (for example using Control-C):
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
public class Program
{
public static async Task Main(string[] args)
{
var hostBuilder = new HostBuilder();
// register your configuration and services.
....
await hostBuilder.RunConsoleAsync();
}
}
In order to run the gRPC service, you need to start/stop Grpc.Core.Server in a hosted service. A hosted service is basically a piece of code that is run by the host when the host itself is started and the same for when it is stopped. This is represented in the IHostedService interface. That's to say, implement a GrpcHostedService to override the interface:
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.Extensions.Hosting;
namespace Grpc.Host
{
public class GrpcHostedService: IHostedService
{
private Server _server;
public GrpcHostedService(Server server)
{
_server = server;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_server.Start();
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken) => await _server.ShutdownAsync();
}
}
It's simple really. We get an GrpcHostedService instance injected through dependency injection and run StartAsync on it when host is started. When the host is stopped we run StopAsync so that we can gracefully shut everything down including Grpc server.
Then go back to the Program.cs and make some changes:
public class Program
{
public static async Task Main(string[] args)
{
var hostBuilder = new HostBuilder()
// Add configuration, logging, ...
.ConfigureServices((hostContext, services) =>
{
// Better to use Dependency Injection for GreeterImpl
Server server = new Server
{
Services = {Greeter.BindService(new GreeterImpl())},
Ports = {new ServerPort("localhost", 5000, ServerCredentials.Insecure)}
};
services.AddSingleton<Server>(server);
services.AddSingleton<IHostedService, GrpcHostedService>();
});
await hostBuilder.RunConsoleAsync();
}
}
By doing this, the generic host will automatically run StartAsync on our hosted service, which in turn will call StartAsync on the Server instance, essentially start the gRPC server.
When we shut down the host with Control-C, the generic host will automatically call StopAsync on our hosted service, which again will call StopAsync on the Server instance which will do some clean up.
For other configuration in HostBuilder, you can see this blog.
| 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 i.e extract the message and run the request on node C. What is that I should look for in between Node A and gRPC server.
Thanks in Advance
| 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 specific situation.
| 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\windows_x64\grpc_csharp_plugin.exe"
No errors output in console
| 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 with test.proto as shown below:
test.proto:
syntax = "proto3";
service StackOverflowService {
rpc GetAnswer(Question) returns (Answer);
}
message Question {
string text = 1;
string user = 2;
repeated string tags = 3;
}
message Answer {
string text = 1;
string user = 2;
}
Then run (all on one line; I've broken it just for readability here):
tools\protoc.exe -I protos protos\test.proto --csharp_out=output
--grpc_out=output --plugin=protoc-gen-grpc=tools\grpc_csharp_plugin.exe
In the output directory, you'll find Test.cs and TestGrpc.cs
| 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 I provide more workers than max concurrent RPCs?
server = grpc.server(
thread_pool=futures.ThreadPoolExecutor(max_workers=1),
maximum_concurrent_rpcs=1,
)
| 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 will be queued and will be processed when a thread finishes its processing.
I had the same question. To answer this, I debugged a bit what happens with maximum_concurrent_rpcs. The debugging went to py36/lib/python3.6/site-packages/grpc/_server.py in my virtualenv. Search for concurrency_exceeded. The bottom line is that if the server is already processing maximum_concurrent_rpcs and another request arrives, it will be rejected:
# ...
elif concurrency_exceeded:
return _reject_rpc(rpc_event, cygrpc.StatusCode.resource_exhausted,
b'Concurrent RPC limit exceeded!'), None
# ...
I tried it with the gRPC Python Quickstart example:
gRPC quick start python example
In the greeter_server.py I modified the SayHello() method:
# ...
def SayHello(self, request, context):
print("Request arrived, sleeping a bit...")
time.sleep(10)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
# ...
and the serve() method:
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), maximum_concurrent_rpcs=2)
# ...
Then I opened 3 terminals and executed the client in them manually (as fast as I could using python greeter_client.py:
As expected, for the first 2 clients, processing of the request started immediately (can be seen in the server's output), because there were plenty of threads available, but the 3rd client got rejected immediately (as expected) with StatusCode.RESOURCE_EXHAUSTED, Concurrent RPC limit exceeded!.
Now to test what happens when there are not enough threads given to ThreadPoolExecutor I modified the max_workers to be 1:
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1), maximum_concurrent_rpcs=2)
I ran my 3 clients again roughly the same time as previously.
The results is that the first one got served immediately. The second one needed to wait 10 seconds (while the first one was served) and then it was served. The third one got rejected immediately.
| 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(credsFile));
TextToSpeechSettings settings = TextToSpeechSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(creds)).build();
textToSpeechClient = TextToSpeechClient.create(settings);
} catch (IOException e) {
e.printStackTrace();
System.exit(-2);
}
if (cmd.hasOption('l')) {
ListVoicesRequest request = ListVoicesRequest.getDefaultInstance();
ListVoicesResponse response = textToSpeechClient.listVoices(request);
List<Voice> voices = response.getVoicesList();
System.out.println("Available voices :");
for (Voice v : voices) {
System.out.printf(" - %s, [%d]: %s/%s", v.getName(), v.getLanguageCodesCount(), v.getLanguageCodes(0), v.getSsmlGender());
}
textToSpeechClient.close();
System.exit(0);
}
I first thought it came from the credentials file. But it's not, the file is correctly located.
And I get this.
avr. 02, 2019 11:36:46 PM io.grpc.internal.ManagedChannelImpl$1 uncaughtException
SEVERE: [Channel<1>: (texttospeech.googleapis.com:443)] Uncaught exception in the SynchronizationContext. Panic!
java.lang.IllegalStateException: Could not find policy 'pick_first'. Make sure its implementation is either registered to LoadBalancerRegistry or included in META-INF/services/io.grpc.LoadBalancerProvider from your jar files.
at io.grpc.internal.AutoConfiguredLoadBalancerFactory$AutoConfiguredLoadBalancer.<init>(AutoConfiguredLoadBalancerFactory.java:93)
at io.grpc.internal.AutoConfiguredLoadBalancerFactory.newLoadBalancer(AutoConfiguredLoadBalancerFactory.java:64)
at io.grpc.internal.ManagedChannelImpl.exitIdleMode(ManagedChannelImpl.java:357)
at io.grpc.internal.ManagedChannelImpl$ChannelTransportProvider$1ExitIdleModeForTransport.run(ManagedChannelImpl.java:455)
at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:101)
at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:130)
at io.grpc.internal.ManagedChannelImpl$ChannelTransportProvider.get(ManagedChannelImpl.java:459)
(...) a whole bunch of other lines
How to fix this error ?
Note that I'm using the latest google-cloud-texttospeech library (version 0.85.0-beta).
| 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 command executed below command
curl -X POST -k https://localhost:10000/v1/echo -d '{"Key": "Value"}'
After making above request, not able to get the proper response.
My doubt is, any server side code changes needed to prepare the response to send back to caller? If so, Please suggest me with the code (Java) & also how to make request. If not, how we need to make http request to grpc?
Working example is much appreciated.
| 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/sourcegraph/gophercon-2018-liveblog/issues/27. There are different ways of doing Reflection across programming languages. My advice is, just do this for the development phase, otherwise, people may querying your gRPC endpoint. Maybe you can use if() to make a conditional block for it. For Golang, i did this
import "google.golang.org/grpc/reflection"
if os.Getenv("GO_ENV") == "development" {
reflection.Register(s)
}
then, you need to know available services in your gRPC server. There is two way you can know the structure. First You can read them from your proto file, second by executing command grpcurl localhost:10000 list
If you like to read from your proto file, the path should be packageName.Service/rpcMethodName. So, based on your proto, it should be something like EchoService/Echo or if you have package name it will be packageName.EchoService/Echo
If you prefer to do grpcurl localhost:10000 list, just type those command and it will output service path.
The last thing to note when you test it locally and you don't setup SSL/TLS, please use -plaintext option, otherwise, it will tell you that TLS handshake failed.
Example command, based on your proto, a call in local will looks like:
grpcurl -plaintext -d '{"Key": "Value"}' 127.0.0.1:10000 EchoService/Echo
Hope it helps.
UPDATE 30 June 2020:
After a few months working with gRPC I found another interesting gRPC tool:
Interactive tool: https://github.com/ktr0731/evans
even easier GUI tool: https://github.com/uw-labs/bloomrpc
| 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, webpack looks for the node modules in that path.
From my client.js
working version:
const {StopRequest, StopReply} = require('./work_pb.js');
Problematic version:
const {StopRequest, StopReply} = require('../../../messages/proto/output/work_pb.js');
In this last case it looks for the node modules in ../../../messages/proto/output/.
The node modules are installed in the current path where my client.js is and from where I ran npx webpack client.js.
ERROR in /home/xxx/yyy/zzz/messages/proto/output/work_pb.js
Module not found: Error: Can't resolve 'google-protobuf' in '/home/xxx/yyy/zzz/messages/proto/output'
@ /home/xxx/yyy/zzz/messages/proto/output/work_pb.js 11:11-37
@ ./client.js
How do I tell webpack to look in the current path for the node modules and not in the path of the compiled proto?
| 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_modules inside your project root (where webpack config resides) take precedence over the default setting "node_modules", which resolves paths via node module resolution algorithm.
More infos: Webpack docs: Module Resolution
| 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 -m grpc.tools.protoc -I$INCLUDE --python_out=$OUTPUT --grpc_python_out=$OUTPUT $PROTO_FILES
Which is not super helpful. I notice there are many limitations. For example using an $OUTPUT of .. just fails silently.
Where can I find documentation on this tool?
| 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 directory in which to search for
imports. May be specified multiple times;
directories will be searched in order. If not
given, the current working directory is used.
--version Show version info and exit.
-h, --help Show this text and exit.
--encode=MESSAGE_TYPE Read a text-format message of the given type
from standard input and write it in binary
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode=MESSAGE_TYPE Read a binary message of the given type from
standard input and write it in text format
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode_raw Read an arbitrary protocol message from
standard input and write the raw tag/value
pairs in text format to standard output. No
PROTO_FILES should be given when using this
flag.
--descriptor_set_in=FILES Specifies a delimited list of FILES
each containing a FileDescriptorSet (a
protocol buffer defined in descriptor.proto).
The FileDescriptor for each of the PROTO_FILES
provided will be loaded from these
FileDescriptorSets. If a FileDescriptor
appears multiple times, the first occurrence
will be used.
-oFILE, Writes a FileDescriptorSet (a protocol buffer,
--descriptor_set_out=FILE defined in descriptor.proto) containing all of
the input files to FILE.
--include_imports When using --descriptor_set_out, also include
all dependencies of the input files in the
set, so that the set is self-contained.
--include_source_info When using --descriptor_set_out, do not strip
SourceCodeInfo from the FileDescriptorProto.
This results in vastly larger descriptors that
include information about the original
location of each decl in the source file as
well as surrounding comments.
--dependency_out=FILE Write a dependency output file in the format
expected by make. This writes the transitive
set of input file paths to FILE
--error_format=FORMAT Set the format in which to print errors.
FORMAT may be 'gcc' (the default) or 'msvs'
(Microsoft Visual Studio format).
--print_free_field_numbers Print the free field numbers of the messages
defined in the given proto files. Groups share
the same field number space with the parent
message. Extension ranges are counted as
occupied fields numbers.
--plugin=EXECUTABLE Specifies a plugin executable to use.
Normally, protoc searches the PATH for
plugins, but you may specify additional
executables not in the path using this flag.
Additionally, EXECUTABLE may be of the form
NAME=PATH, in which case the given plugin name
is mapped to the given executable even if
the executable's own name differs.
--grpc_python_out=OUT_DIR Generate Python source file.
--python_out=OUT_DIR Generate Python source file.
@<filename> Read options and filenames from file. If a
relative file path is specified, the file
will be searched in the working directory.
The --proto_path option will not affect how
this argument file is searched. Content of
the file will be expanded in the position of
@<filename> as in the argument list. Note
that shell expansion is not applied to the
content of the file (i.e., you cannot use
quotes, wildcards, escapes, commands, etc.).
Each line corresponds to a single argument,
even if it contains spaces.
| 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(HelloRequest) returns (HelloResponse);
}
It generates the file normally
User.java -> generated from protoc compiler
userGrpc.java -> generated from protoc compiler
GRPCService.java
package GRPCService;
import java.io.IOException;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import user.UserService;
public class GPRCService {
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(9091).addService(new UserService()).build();
server.start();
System.out.println("Server started at " + server.getPort());
server.awaitTermination();
}
}
The system.out.println showing the server is running;
Server started at 9091
And then I opened the firewall rule for TCP on port 9091 on ubuntu 18.04
sudo ufw allow from any to any port 9091 proto tcp
Results:
java 28277 ubuntu 49u IPv6 478307 0t0 TCP *:9091 (LISTEN)
I can even curl from the terminal
* Rebuilt URL to: http://localhost:9091/
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9091 (#0)
> GET / HTTP/1.1
> Host: localhost:9091
> User-Agent: curl/7.58.0
> Accept: */*
>
Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file.
* Failed writing body (0 != 40)
* stopped the pause stream!
* Closing connection 0
Curl command
curl -v http://localhost:9091
But when executinng from the gui client
https://github.com/gusaul/grpcox
I get a connection refused.
dial tcp 127.0.0.1:9091: connect: connection refused
I am not using any VPN nor proxy and the GUI app is actually running inside a container.
docker run -p 6969:6969 -v {ABSOLUTE_PATH_TO_LOG}/log:/log -d gusaul/grpcox
If somebody could please help me.
Thank you Stack !
| 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 network access, run the container...
docker run --net=host ... gusaul/grpcox
| 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) {
// process a data
@Override
public void onError(Throwable t) {
}
@Override
public void onCompleted() {
}
});
} catch (StatusRuntimeException e) {
LOG.warn("RPC failed: {}", e.getStatus());
}
Thread.currentThread().join();
server service:
public class Sender extends DataServiceGrpc.DataServiceImplBase implements Runnable {
private final BlockingQueue<Data> queue;
private final static HashSet<StreamObserver<Data>> observers = new LinkedHashSet<>();
public Sender(BlockingQueue<Data> queue) {
this.queue = queue;
}
@Override
public void data(Empty request, StreamObserver<Data> responseObserver) {
observers.add(responseObserver);
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// waiting for first element
Data data = queue.take();
// send head element
observers.forEach(o -> o.onNext(data));
} catch (InterruptedException e) {
LOG.error("error: ", e);
Thread.currentThread().interrupt();
}
}
}
}
How to remove clients from global observers properly? How to received some sort of a signal when connection drops?
How to manage client-server reconnections? How to force client reconnect when connection drops?
Thanks in advance!
| 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 generated code is simplified to pass in the the request directly. This means that you don't have direct access to the underlying ServerCall.Listener, which is how you would normally listen for clients disconnecting and cancelling.
Instead, every gRPC call has a Context associated with it, which carries the cancellation and other request-scoped signals. For your case, you just need to listen for cancellation by adding your own listener, which then safely removes the response observer from your linked hash set.
As for reconnects: gRPC clients will automatically reconnect if the connection is broken, but usually will not retry the RPC unless it is safe to do so. In the case of server streaming RPCs, it is usually not safe to do, so you'll need to retry the RPC on your client directly.
| 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.
See here for examples of both:
https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md
| 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 MVC and the gRPC on both endpoints and I don't want that. This is because I need the Grpc requests use Http2. On the other hand, I need that MVC requests use Http1
on my Statup.cs I have
public void Configure(IApplicationBuilder app)
{
// ....
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<ComunicacaoService>();
endpoints.MapControllerRoute("default",
"{controller}/{action=Index}/{id?}");
});
// ...
I need a way to make endpoints.MapGrpcService<ComunicacaoService>(); be published on one socket and the endpoints.MapControllerRoute("default","{controller}/{action=Index}/{id?}"); on another one.
| 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, cfg =>
{
cfg.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
});
options.Listen(IPAddress.Loopback, 55002, cfg =>
{
cfg.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1;
});
});
webBuilder.UseStartup<Startup>();
});
Alternatively in appsettings.json:
"Kestrel": {
"Endpoints": {
"Grpc": {
"Protocols" : "Http2",
"Url": "http://localhost:55001"
},
"webApi": {
"Protocols": "Http1",
"Url": "http://localhost:55002"
}
}
}
| 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" no matter which protocol (http/https) and port I use. gRPC should be using 5001 and webapi using 8001.
heres my startup class:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<BootNodeService>();
endpoints.MapControllers();
});
}
}
And my controller:
[ApiController]
[Route("[controller]")]
public class AdminController : ControllerBase
{
[HttpGet] public string Get()
{ return "hello"; }
}
Any thoughts?
Thnx
EDIT: the entire project can be found at this repo.
EDIT: view of screen
| 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:
public class Program
{
public static void Main(string[] args)
{
IHostBuilder hostBuilder = CreateHostBuilder(args);
IHost host = hostBuilder.Build();
host.Run();
}
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options =>
{
options.ListenLocalhost(5001, o => o.Protocols =
HttpProtocols.Http2);
// ADDED THIS LINE to fix the problem
options.ListenLocalhost(11837, o => o.Protocols =
HttpProtocols.Http1);
});
webBuilder.UseStartup<Startup>();
});
}
}
Thnx
| 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 HTTP/1.1 instead of HTTP/2 on the server side, but I cannot find any information how to achieve that.
Is it possible to use HTTP/1.1 for gRPC server written in .NET Core? And if so - how?
| 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-side, there is virtually no difference between the two; only the actual channel creation changes, between:
GrpcChannel.ForAddress(...)
with the Microsoft transport, and
new Channel(...)
with the Google transport. All of the rest of the APIs are shared (in Grpc.Core.Api)
| 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 the main thread until the server processes it and the result is sent back.
What I need to do is create a client that can make one RPC call, and then start another while waiting for the result of the first to come back from the server.
I've got no idea how to go about that.
Does anyone have a working example, or can anyone describe how to actually use gRPC asynchronously?
Their example code:
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include <grpc/support/log.h>
#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif
using grpc::Channel;
using grpc::ClientAsyncResponseReader;
using grpc::ClientContext;
using grpc::CompletionQueue;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;
class GreeterClient {
public:
explicit GreeterClient(std::shared_ptr<Channel> channel)
: stub_(Greeter::NewStub(channel)) {}
// Assembles the client's payload, sends it and presents the response back
// from the server.
std::string SayHello(const std::string& user) {
// Data we are sending to the server.
HelloRequest request;
request.set_name(user);
// Container for the data we expect from the server.
HelloReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The producer-consumer queue we use to communicate asynchronously with the
// gRPC runtime.
CompletionQueue cq;
// Storage for the status of the RPC upon completion.
Status status;
// stub_->PrepareAsyncSayHello() creates an RPC object, returning
// an instance to store in "call" but does not actually start the RPC
// Because we are using the asynchronous API, we need to hold on to
// the "call" instance in order to get updates on the ongoing RPC.
std::unique_ptr<ClientAsyncResponseReader<HelloReply> > rpc(
stub_->PrepareAsyncSayHello(&context, request, &cq));
// StartCall initiates the RPC call
rpc->StartCall();
// Request that, upon completion of the RPC, "reply" be updated with the
// server's response; "status" with the indication of whether the operation
// was successful. Tag the request with the integer 1.
rpc->Finish(&reply, &status, (void*)1);
void* got_tag;
bool ok = false;
// Block until the next result is available in the completion queue "cq".
// The return value of Next should always be checked. This return value
// tells us whether there is any kind of event or the cq_ is shutting down.
GPR_ASSERT(cq.Next(&got_tag, &ok));
// Verify that the result from "cq" corresponds, by its tag, our previous
// request.
GPR_ASSERT(got_tag == (void*)1);
// ... and that the request was completed successfully. Note that "ok"
// corresponds solely to the request for updates introduced by Finish().
GPR_ASSERT(ok);
// Act upon the status of the actual RPC.
if (status.ok()) {
return reply.message();
} else {
return "RPC failed";
}
}
private:
// Out of the passed in Channel comes the stub, stored here, our view of the
// server's exposed services.
std::unique_ptr<Greeter::Stub> stub_;
};
int main(int argc, char** argv) {
// Instantiate the client. It requires a channel, out of which the actual RPCs
// are created. This channel models a connection to an endpoint (in this case,
// localhost at port 50051). We indicate that the channel isn't authenticated
// (use of InsecureChannelCredentials()).
GreeterClient greeter(grpc::CreateChannel(
"localhost:50051", grpc::InsecureChannelCredentials()));
std::string user("world");
std::string reply = greeter.SayHello(user); // The actual RPC call!
std::cout << "Greeter received: " << reply << std::endl;
return 0;
}
| 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 sending to the server.
HelloRequest request;
request.set_name(user);
// Call object to store rpc data
AsyncClientCall* call = new AsyncClientCall;
call->response_reader =
stub_->PrepareAsyncSayHello(&call->context, request, &cq_);
// StartCall initiates the RPC call
call->response_reader->StartCall();
call->response_reader->Finish(&call->reply, &call->status, (void*)call);
}
Client Async receive function:
// Loop while listening for completed responses.
// Prints out the response from the server.
void AsyncCompleteRpc() {
void* got_tag;
bool ok = false;
// Block until the next result is available in the completion queue "cq".
while (cq_.Next(&got_tag, &ok)) {
// The tag in this example is the memory location of the call object
AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
if (call->status.ok())
std::cout << "Greeter received: " << call->reply.message() << std::endl;
else
std::cout << "RPC failed" << std::endl;
// Once we're complete, deallocate the call object.
delete call;
}
}
Main function:
int main(int argc, char** argv) {
GreeterClient greeter(grpc::CreateChannel(
"localhost:50051", grpc::InsecureChannelCredentials()));
// Spawn reader thread that loops indefinitely
std::thread thread_ = std::thread(&GreeterClient::AsyncCompleteRpc, &greeter);
for (int i = 0; i < 100; i++) {
std::string user("world " + std::to_string(i));
greeter.SayHello(user); // The actual RPC call!
}
std::cout << "Press control-c to quit" << std::endl << std::endl;
thread_.join(); //blocks forever
return 0;
}
addition
As @nmgeek noted, there is a potential memory leak in this solution, please see memory-leak-in-grpc-async-client.
| 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(GetTracksRequest request, StreamObserver < GetTracksResponse > responseObserver) {
GetTracksResponse reply = GetTracksResponse
.newBuilder()
.addTracks(TrackInfo.newBuilder()
.setOwner("test")
.setTrackName("test")
.build())
.build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
| 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 = "DummyProto";
option objc_class_prefix = "DMYS";
package dummy;
import "general.proto";
// The dummy service definition.
service DummyService {
// # Misc
// Returns the server version
rpc getVersion (Empty) returns (ServerVersion) {}
// Returns the java version
rpc getJava (Empty) returns (JavaVersion) {}
}
// Transmission data types
(The following file is included above:)
syntax = "proto3";
option java_multiple_files = true;
option java_package = "general";
option java_outer_classname = "General";
option objc_class_prefix = "G";
// Transmission data types
message Empty {} // Empty Request or Reply
message ServerVersion {
string version = 1;
}
message JavaVersion {
string version = 1;
}
The DummyService based on the generated Java from the Protoc compiler is the following:
package servers.dummy;
import java.util.logging.Logger;
import general.Empty;
import general.JavaVersion;
import general.ServerVersion;
import io.grpc.stub.StreamObserver;
public class DummyService extends DummyServiceGrpc.DummyServiceImplBase {
private static final Logger logger = Logger.getLogger(DummyService.class.getName());
@Override
public void getVersion(Empty req, StreamObserver<ServerVersion> responseObserver) {
logger.info("Server Version-Request received...");
ServerVersion version = ServerVersion.newBuilder().setVersion("1.0.0").build();
responseObserver.onNext(version);
responseObserver.onCompleted();
}
@Override
public void getJava(Empty req, StreamObserver<JavaVersion> responseObserver) {
logger.info("Java Version Request received...");
JavaVersion version = JavaVersion.newBuilder().setVersion(Runtime.class.getPackage().getImplementationVersion() + " (" + Runtime.class.getPackage().getImplementationVendor() + ")").build();
responseObserver.onNext(version);
responseObserver.onCompleted();
}
}
Now we build an InProcessServer that runs our Dummy service (or any other service you want to test):
package servers;
import io.grpc.Server;
import io.grpc.inprocess.InProcessServerBuilder;
import java.io.IOException;
import java.util.logging.Logger;
import servers.util.PortServer;
/**
* InProcessServer that manages startup/shutdown of a service within the same process as the client is running. Used for unit testing purposes.
* @author be
*/
public class InProcessServer<T extends io.grpc.BindableService> {
private static final Logger logger = Logger.getLogger(PortServer.class.getName());
private Server server;
private Class<T> clazz;
public InProcessServer(Class<T> clazz){
this.clazz = clazz;
}
public void start() throws IOException, InstantiationException, IllegalAccessException {
server = InProcessServerBuilder
.forName("test")
.directExecutor()
.addService(clazz.newInstance())
.build()
.start();
logger.info("InProcessServer started.");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
InProcessServer.this.stop();
System.err.println("*** server shut down");
}
});
}
void stop() {
if (server != null) {
server.shutdown();
}
}
/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
public void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
}
We can now test the service using the following unit test:
package servers;
import static org.junit.Assert.*;
import general.ServerVersion;
import io.grpc.ManagedChannel;
import io.grpc.StatusRuntimeException;
import io.grpc.inprocess.InProcessChannelBuilder;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import servers.dummy.DummyService;
import servers.dummy.DummyServiceGrpc;
import servers.dummy.DummyServiceGrpc.DummyServiceBlockingStub;
import servers.dummy.DummyServiceGrpc.DummyServiceStub;
public class InProcessServerTest {
private static final Logger logger = Logger.getLogger(InProcessServerTest.class.getName());
private InProcessServer<DummyService> inprocessServer;
private ManagedChannel channel;
private DummyServiceBlockingStub blockingStub;
private DummyServiceStub asyncStub;
public InProcessServerTest() {
super();
}
@Test
public void testInProcessServer() throws InterruptedException{
try {
String version = getServerVersion();
assertEquals("1.0.0", version);
} finally {
shutdown();
}
}
/** Ask for the server version */
public String getServerVersion() {
logger.info("Will try to get server version...");
ServerVersion response;
try {
response = blockingStub.getVersion(null);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
fail();
return "";
}
return response.getVersion();
}
@Before
public void beforeEachTest() throws InstantiationException, IllegalAccessException, IOException {
inprocessServer = new InProcessServer<DummyService>(DummyService.class);
inprocessServer.start();
channel = InProcessChannelBuilder
.forName("test")
.directExecutor()
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext(true)
.build();
blockingStub = DummyServiceGrpc.newBlockingStub(channel);
asyncStub = DummyServiceGrpc.newStub(channel);
}
@After
public void afterEachTest(){
channel.shutdownNow();
inprocessServer.stop();
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
}
The test does only test one of two methods, as it is just for illustration purposes. The other method can be tested accordingly.
See the RouteGuideExample for more information on how to test both server and client:
https://github.com/grpc/grpc-java/blob/master/examples/src/test/java/io/grpc/examples/routeguide/RouteGuideServerTest.java
| 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 the calling to the server. I would like this Classify to time-out after 5 seconds or so. Any help or direction would be appreciated.
channel = new Channel(modelServer, ChannelCredentials.Insecure);
var client = MyService.NewClient(channel);
MyResponse classvalue = client.Classify(featureSet);
| 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.RouteGuideBlockingStub;
import io.grpc.examples.routeguide.RouteGuideGrpc.RouteGuideStub;
...
...
blockingStub = RouteGuideGrpc.newBlockingStub(channel);
asyncStub = RouteGuideGrpc.newStub(channel);
However I cannot find these classes in their repo. I am still hazy on exactly what they are for, should they have been produced when compiling the .proto file? Any help/pointers would be appreciated. Thanks.
| 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 currently running thread) and ensure that the rpc call invoked on it doesn't return until it returns a response or raises an exception. Care should be taken not to invoke an rpc on a blocking stub from the UI thread as this will result in an unresponsive/janky UI.
Asynchronous stubs make non-blocking rpc calls where the response is returned asynchronously via a StreamObserver callback object.
For more information, refer to the grpc documentation regarding stubs here.
| 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)
except grpc.FutureTimeoutError:
sys.exit('Error connecting to server')
else:
stub = MyService_pb2_grpc.MyServiceStub(channel)
print('Connected to gRPC server.')
this_is_just_read_maybe(stub)
def this_is_just_read_maybe(stub):
responses = stub.MyEventStream(stream())
for response in responses:
print(f'Received message: {response}')
if response.something:
# okay, now what? how do i send a message here?
def stream():
yield my_start_stream_msg
# this is fine, i receive this server-side
# but i can't check for incoming messages here
I don't seem to have a read() or write() on the stub, everything seems to be implemented with iterators.
How do i send a message from this_is_just_read_maybe(stub)?
Is that even the right approach?
My Proto is a bidirectional stream:
service MyService {
rpc MyEventStream (stream StreamingMessage) returns (stream StreamingMessage) {}
}
| 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(StreamingMessage())
# receive
response = next(my_event_stream) # type: StreamingMessage
This makes use of the sentinel form of iter, which converts a regular function into an iterator that stops when it reaches a sentinel value (in this case None).
| 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. Then I run it like ./dist/hello/hello and I get error ImportError: No module named grpc.
So then I installed grpc using pip install grpc. When I rebuild the artifact I now get error Import grpc:No module named gevent.socket.
Reading online indicated that the correct items to install were actually grpcio and grpcio-tools. So I tried pip uninstall grpc pip install grpcio and pip install grpcio-tools. Doing this and rebuilding the artifact gave me error ImportError: No module named pkg_resources. Trying to pip install pkg_resources gives error: Could not find a version that satisfies the requirement pkg_resources
Having all grpcio grpcio-tools and grpc install gives the same error: Import grpc:No module named gevent.socket
This seems like it should be a very simple task. I simply want to use pyinstaller to build an artifact that has a dependency on grpc, how do I do this?
| 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 {
string id = 1;
string description = 2;
int32 weight = 3;
repeated Container containers = 4;
string vessel_id = 5;
}
message Container {
string id = 1;
string customer_id = 2;
string origin = 3;
string user_id = 4;
}
message Response {
bool created = 1;
Consignment consignment = 2;
}
This is the struct in the .pb.go file. Can someone tell me why are there 3 XXX types in my struct? Shouldn't the struct be reflecting what I'm defining in my proto?
type Consignment struct {
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"`
Weight int32 `protobuf:"varint,3,opt,name=weight" json:"weight,omitempty"`
Containers []*Container `protobuf:"bytes,4,rep,name=containers" json:"containers,omitempty"`
VesselId string `protobuf:"bytes,5,opt,name=vessel_id,json=vesselId" json:"vessel_id,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
| 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. This is a feature to help with backwards compatibility between clients and serves built at different times.
Additionally, the XXX fields allow you to expose extensions, which were part of Proto2. They were removed in Proto3 in favor of Any, but the library still needs to support them.
As for what you should do with these? I would just leave them alone, and don't reference them. You don't need to set them, and you don't need to read them. The Go protobuf library will handle them for you.
| 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 := grpc.NewServer()
pb.RegisterSubscriberServiceServer(grpcServer, &subscriberServer{})
pb.RegisterDropperServiceServer(grpcServer, &dropperServer{})
l, err := net.Listen("tcp", ":6000")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
log.Println("Listening on tcp://localhost:6000")
grpcServer.Serve(l)
}
Why do I need to dial a different socket for each grpc service?
type DropperRPC struct {
conn *grpc.ClientConn
client pb.DropperServiceClient
chunkSize int
}
type SubscriberRPC struct {
conn *grpc.ClientConn
client pb.SubscriberServiceClient
chunkSize int
}
func NewSubscriber() (c SubscriberRPC, err error) {
c.conn, err = grpc.Dial("localhost:6000", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
c.client = pb.NewSubscriberServiceClient(c.conn)
return
}
func NewDropper() (c DropperRPC, err error) {
c.conn, err = grpc.Dial("localhost:6000", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
c.client = pb.NewDropperServiceClient(c.conn)
return
}
And since the code is basically duplicated to accommodate each service, can't I just use an Interface to reduce the code?
func main() {
c1, err := NewSubscriber()
if err != nil {
log.Fatal(err)
}
c2, err := NewDropper()
if err != nil {
log.Fatal(err)
}
cc1 := &c1
cc2 := &c2
}
And then use this Interface to implement the client side grpc functions for each service, instead of creating a new struct for each service. I have found cmux , but there must be a way to do this without using external libraries.
|
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.Fatal(err)
}
c1 := pb.NewSubscriberServiceClient(cc)
c2 := pb.NewDropperServiceClient(cc)
}
And then use this Interface to implement the client side grpc functions for each service, instead of creating a new struct for each service
The generated code in the pb.go file does everything you need to perform RPCs. You shouldn't have to implement anything client-side unless you have special logic you want to happen automatically every time you perform a call.
If the two services have unique method names, you could put them into the same struct so you don't have to use them separately, as a minor convenience:
type SubscriberDropper struct {
pb.SubscriberServiceClient
pb.DropperServiceClient
}
func main() {
// ... as above ...
sd := &SubscriberDropper{c1, c2}
}
| 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 waiting or timeout) and consistent.
This includes all of the official gRPC examples, all of them build and run out of the box, but fail to call the server with that error. For example:
// Server
Server server = new Server
{
Services = { Greeter.BindService(new GreeterImpl()) },
Ports = { new ServerPort("localhost", 50051, ServerCredentials.Insecure) }
};
server.Start();
Console.ReadKey();
server.ShutdownAsync().Wait();
// Client
Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
var client = new Greeter.GreeterClient(channel);
var reply = client.SayHello(new HelloRequest { Name = "you" });
I also tried to call the server with the BloomRPC client, with the same error message.
The server service implementation is not called and nothing is written in server logs (with GRPC_TRACE=all and GRPC_VERBOSITY=debug). Here are full client logs with the same settings. Notable excerpt:
D0418 14:53:48.801298 0 ...: set_final_status CLI
D0418 14:53:48.801545 0 ...: {"created":"@1555592028.801000000","description":"Error received from peer","file":"...","file_line":1036,"grpc_message":"Stream removed","grpc_status":2}
I0418 14:53:48.802018 0 ...: ipv4:10.240.240.1:8080: Complete BDP ping err={"created":"@1555592028.790000000","description":"OS Error","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\lib\iomgr\tcp_windows.cc","file_line":344,"os_error":"An established connection was aborted by the software in your host machine.\r\n","syscall":"WSASend","wsa_error":10053}
The server's port appears open in Resource Manager, I am able to invoke the server with telnet and it responds with a few bytes of non-text data (and disconnects as soon as I send any input).
I tried various combinations of host addresses for both client and server ("localhost", "127.0.0.1", "0.0.0.0", my machine's name or IP within the local network), all to the same end.
This is happening on up-to-date Win10, VS 2017, .Net Core 2.1 (happens with 2.0 too). Windows Firewall is disabled. I often develop with other networking technologies (eg. WCF) on this machine and have never faced any such issues.
Interestingly enough, the same exact code works correctly on my home machine out of the box, so it has to be something about the system, but I have been unable to determine what.
EDIT: I experiemented with communication between these C# client and server and an analogous client server in Java (from grpc-java examples).
My observations:
Java client CAN call C# server.
C# client CAN'T call Java server
Java client CAN call Java server
C# client CAN'T call C# server.
This produces a simple conclusion: The issue is with the C# client, though I have no explanation why it works on other computers (I have tested it at my colleagues's computer as well and it does work there).
| 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 older .NET Frameworks). To get it fixed, on Server side of gRPC I've made this change (I hope this helps someone):
From:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
To:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options =>
{
// This endpoint will use HTTP/2 and HTTPS on port 5001.
options.Listen(IPAddress.Any, 5001, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
});
});
webBuilder.UseStartup<Startup>();
});
| 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 definition?
I have tried using below definition but it didn't work.
message UserRequest{
string name = 1;
string city = 2;
string email = 3;
google.protobuf.Any metainfo = 4;
}
| 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:
.google.protobuf.Struct metainfo = 4;
| 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. HttpRequestException: Requesting HTTP version 2.0
with version policy RequestVersionOrHigher while HTTP/2 is not
enabled."
This occurs whether or not the server application is running. Here is the code I'm using to make the call:
using var channel = GrpcChannel.ForAddress(@"http://localhost:5000");
var client = new AlgorithmRunner.AlgorithmRunnerClient(channel);
using var call = client.RunAlgorithm(new RunAlgorithmRequest());
while (await call.ResponseStream.MoveNext())
{
}
My understanding is that .NET 5 gRPC is supposed to have HTTP/2 enabled by default: why does the exception indicate that HTTP/2 is not enabled and how do I resolve it?
| 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 interfering with HTTP/2 (unsupported?), preventing gRPC from working correctly. The workaround for local development is to manually set the default proxy for the HttpClient before making the gRPC call:
HttpClient.DefaultProxy = new WebProxy();
using var channel = GrpcChannel.ForAddress(@"http://localhost:5000");
var client = new AlgorithmRunner.AlgorithmRunnerClient(channel);
using var call = client.RunAlgorithm(new RunAlgorithmRequest());
This may represent a general problem with using gRPC through certain types of proxies.
| 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 userClassPathFirst to true on spark, but leads to other errors.
Correct me if I am wrong, but from what I understand, I shouldn't have to set userClassPathFirst to true if I do shading correctly. Here's how I do shading now:
assemblyShadeRules in assembly := Seq(
ShadeRule.rename("com.google.guava.**" -> "my_conf.@1")
.inLibrary("com.google.guava" % "guava" % "20.0")
.inLibrary("io.grpc" % "grpc-netty" % "1.1.2")
)
libraryDependencies ++= Seq(
"org.scalaj" %% "scalaj-http" % "2.3.0",
"org.json4s" %% "json4s-native" % "3.2.11",
"org.json4s" %% "json4s-jackson" % "3.2.11",
"org.apache.spark" %% "spark-core" % "2.2.0" % "provided",
"org.apache.spark" % "spark-sql_2.11" % "2.2.0" % "provided",
"org.clapper" %% "argot" % "1.0.3",
"com.typesafe" % "config" % "1.3.1",
"com.databricks" %% "spark-csv" % "1.5.0",
"org.apache.spark" % "spark-mllib_2.11" % "2.2.0" % "provided",
"io.grpc" % "grpc-netty" % "1.1.2",
"com.google.guava" % "guava" % "20.0"
)
What am I doing wrong here and how do I fix it?
| 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/guava-20.0.jar | sed -e 's:/[^/]*$::' | sort | uniq
META-INF
META-INF/maven
META-INF/maven/com.google.guava
META-INF/maven/com.google.guava/guava
com
com/google
com/google/common
com/google/common/annotations
com/google/common/base
com/google/common/base/internal
com/google/common/cache
com/google/common/collect
com/google/common/escape
com/google/common/eventbus
com/google/common/graph
com/google/common/hash
com/google/common/html
com/google/common/io
com/google/common/math
com/google/common/net
com/google/common/primitives
com/google/common/reflect
com/google/common/util
com/google/common/util/concurrent
com/google/common/xml
com/google/thirdparty
com/google/thirdparty/publicsuffix
It should be enough to change your shading rule to this:
assemblyShadeRules in assembly := Seq(
ShadeRule.rename("com.google.common.**" -> "my_conf.@1")
.inLibrary("com.google.guava" % "guava" % "20.0")
.inLibrary("io.grpc" % "grpc-netty" % "1.1.2")
)
So you don't need to change userClassPathFirst.
Moreover, you can simplify your shading rule like this:
assemblyShadeRules in assembly := Seq(
ShadeRule.rename("com.google.common.**" -> "my_conf.@1").inAll
)
Since org.apache.spark dependencies are provided, they will not be included in your jar and will not be shaded (hence spark will use its own unshaded version of guava that it has on the cluster).
| 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_obj> mapObj1 = 1;
map<uint32, value_obj> mapObj2 = 2;
}
I tried creating objects in Python like below:
obj = list_of_maps()
mapObjToStore = value_obj()
mapObjToStore.code = 10
obj.mapObj1[1].CopyFrom(mapObjToStore)
When I try to receive the message in server, I get wrong values (huge numbers!).
Any help on this will be greatly appreciated.
| 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(), grpc.WithBlock())
pb.NewAppClient(connection)
defer connection.Close()
and calls are made with a timeout like
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
client.MyGRPCMethod(ctx, params)
One other thing I'm doing is checking the connection to see if it's either open, idle or connecting, and reusing the connection if so. Otherwise, redialing.
Nothing special configuration is happening with the server
grpc.NewServer()
Are there any common mistakes setting up a grpc client/server that I might be making?
| 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 intermediary load-balancers/reverse-proxies (by Cloud Providers or otherwise) and how they manage TCP sockets
Your application layer itself and it's networking requirements - whether it can reuse the same connection for future requests not
My solution turned out to be fairly simple:
server = grpc.NewServer(
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: 5 * time.Minute, // <--- This fixes it!
}),
)
This ensures that the gRPC server closes the underlying TCP socket gracefully itself before any abrupt kills from the kernel or intermediary servers (AWS and Google Cloud Load Balancers both have larger timeouts than 5 minutes).
The added bonus you will find here is also that any places where you're using multiple connections, any leaks introduced by clients that forget to Close the connection will also not affect your server.
My $0.02: Don't blindly trust any organisation's (even Google's) ability to design and maintain API. This is a classic case of defaults-gone-wrong.
| 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 =>
{
configure.Run(async e =>
{
Console.WriteLine("Exception test code");
});
});
But both of them are not working (not intercepting code).
Is it possible to add global exception handler for gRPC services in ASP.NET Core?
I don't want to write try-catch code wrapper for each method I want to call.
| 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;
using Grpc.Core.Interceptors;
using Microsoft.Extensions.Logging;
namespace Systemx.WebService.Services
{
public class ServerLoggerInterceptor : Interceptor
{
private readonly ILogger<ServerLoggerInterceptor> _logger;
public ServerLoggerInterceptor(ILogger<ServerLoggerInterceptor> logger)
{
_logger = logger;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
//LogCall<TRequest, TResponse>(MethodType.Unary, context);
try
{
return await continuation(request, context);
}
catch (Exception ex)
{
// Note: The gRPC framework also logs exceptions thrown by handlers to .NET Core logging.
_logger.LogError(ex, $"Error thrown by {context.Method}.");
throw;
}
}
}
}
| 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() {
// Spawn a new CallData instance to serve new clients.
new CallData(&service_, cq_.get());
void* tag; // uniquely identifies a request.
bool ok;
int i = 0;
while (true) {
std::cout << i << std::endl; ///////////////////////////////
// Block waiting to read the next event from the completion queue. The
// event is uniquely identified by its tag, which in this case is the
// memory address of a CallData instance.
// The return value of Next should always be checked. This return value
// tells us whether there is any kind of event or cq_ is shutting down.
GPR_ASSERT(cq_->Next(&tag, &ok));
GPR_ASSERT(ok);
static_cast<CallData*>(tag)->Proceed();
i++;
}
}
and inside the proceed() function:
void Proceed() {
if (status_ == CREATE) {
// Make this instance progress to the PROCESS state.
status_ = PROCESS;
// As part of the initial CREATE state, we *request* that the system
// start processing SayHello requests. In this request, "this" acts are
// the tag uniquely identifying the request (so that different CallData
// instances can serve different requests concurrently), in this case
// the memory address of this CallData instance.
std::cout<<"RequestSayHello called"<<std::endl; ////////////////////////////
service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
this);
} else if (status_ == PROCESS) {
// Spawn a new CallData instance to serve new clients while we process
// the one for this CallData. The instance will deallocate itself as
// part of its FINISH state.
new CallData(service_, cq_);
// The actual processing.
std::string prefix("Hello ");
reply_.set_message(prefix + request_.name());
// And we are done! Let the gRPC runtime know we've finished, using the
// memory address of this instance as the uniquely identifying tag for
// the event.
status_ = FINISH;
responder_.Finish(reply_, Status::OK, this);
} else {
std::cout<<"deallocated"<<std::endl; ////////////////////////////
GPR_ASSERT(status_ == FINISH);
// Once in the FINISH state, deallocate ourselves (CallData).
delete this;
}
}
Once I run the server and the one client ( client) then the server prints the following:
RequestSayHello called
i = 0
RequestSayHello called
i = 1
deallocated
i = 2
The second RequestSayHello called makes sense because of the creation of new CallData instance.
My question is how come proceed()function executed the second time and deallocated gets printed?
| 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 mentioned
2. The responder_ is called with the reply object; this inserts a response event into cq_
Upon receiving the response event from cq_, proceed() is called again on the first CallData object, which is now in the FINISH state, so clean up is performed and deallocated is printed.
| 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 files are consuming from different microservices.
Assume, I am going to change the Protofile2 and push the changes to proto repository, remember proto files repository are separated from microservices repository:
When I run go test on service1 or service2, it should tell me, that Protofile2 has changed or does not have the same hash like proto file in the service2 folder:
That I have to generate the code again.
Does it exist any tools to solve the problem? Or how should I solve it?
| 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.com/me/myproto/protodef2"
use go modules (introduced with go v1.11 in 2019) to ensure micro-service X gets a compatible version of protobuf Y
To point 2 - and as @PaulHankin mentioned - try not to break backward compatibility. Protobuf fields can be removed, but as long as the remaining field indices are unaltered, old client calls will still be compatible with newer proto defs.
| 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.dateFromString("2016-02-29 12:24:26")
print(date)
| 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 --> MMM d, h:mm a
September 2018 --> MMMM yyyy
Sep 12, 2018 --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000 --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000 --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18 --> dd.MM.yy
10:41:02.112 --> HH:mm:ss.SSS
Here are alternatives:
Era: G (AD), GGGG (Anno Domini)
Year: y (2018), yy (18), yyyy (2018)
Month: M, MM, MMM, MMMM, MMMMM
Day of month: d, dd
Day name of week: E, EEEE, EEEEE, EEEEEE
| 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.json and contains the following:
{
"person":[
{
"name": "Bob",
"age": "16",
"employed": "No"
},
{
"name": "Vinny",
"age": "56",
"employed": "Yes"
}
]
}
The file is stored in the documents directly and I access it using the following code:
let file = "test.json"
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
NSSearchpathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainMask,
true) as String[]
if (dirs != nil) {
let directories: String[] = dirs
let dir = directories[0]
let path = dir.stringByAppendingPathComponent(file)
}
var jsonData = NSData(contentsOfFile:path, options: nil, error: nil)
println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.
var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary
println("jsonDict \(jsonDict)") - This prints nil.....
If anyone can just give me a push in the right direction on how I can de-serialize the JSON file and put it in an accessible Swift object I will be eternally grateful!
Kind Regards,
Krivvenz.
| 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: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
if let persons : NSArray = jsonResult["person"] as? NSArray
{
// Do stuff
}
}
}
}
The array "persons" will contain all data for key person. Iterate throughs to fetch it.
Swift 4.0:
if let path = Bundle.main.path(forResource: "test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
// do stuff
}
} catch {
// handle error
}
}
| 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
(<_UIAlertControllerActionSheetRegularPresentationController: 0x7fc7a874bd90>)
should have a non-nil sourceView or barButtonItem set before the presentation occurs.
I am using following code for iPhone and iPad for both iOS 7 as well as iOS 8
NSData *myData = [NSData dataWithContentsOfFile:_filename];
NSArray *activityItems = [NSArray arrayWithObjects:myData, nil];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:nil applicationActivities:nil];
activityViewController.excludedActivityTypes = @[UIActivityTypeCopyToPasteboard];
[self presentViewController:activityViewController animated:YES completion:nil];
I am getting a similar crash in of one my other app as well. Can you please guide me ? has anything changed with UIActivityViewController in iOS 8? I checked but i did not find anything on this
| 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 will need to obtain a reference to the UIActivityController's UIPopoverPresentationController and set one of the properties as follows:
if ( [activityViewController respondsToSelector:@selector(popoverPresentationController)] ) {
// iOS8
activityViewController.popoverPresentationController.sourceView =
parentView;
}
| 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, animations: {
self.nameInputConstraint.constant = 8
}, completion: {
(value: Bool) in
println(">>> move const")
})
This works, but it seems to just happen instantly and there doesn't seem to be any movement. I tried to set it 10 seconds to make sure I wasn't missing anything, but I got the same results.
nameInputConstraint is the name of the constraint that I control dragged to connect into my class from IB.
| 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)
This returns an optional, so in cases like passing in "foo" where doubleValue would have returned 0, the failable intializer will return nil. You can use a guard, if-let, or map to handle the Optional<Double>
Original Post:
You don't need to use the NSString constructor like the accepted answer proposes. You can simply bridge it like this:
(swiftString as NSString).doubleValue
| 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 "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.
| 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 Python's type()
dynamicType (see this question)
Update: this has been changed in a recent version of Swift, obj.dynamicType now gives you a reference to the type and not the instance of the dynamic type.
This one seems the most promising, but I haven't been able to find out the actual type so far.
class MyClass {
var count = 0
}
let mc = MyClass()
# update: this now evaluates as true
mc.dynamicType === MyClass.self
I also tried using a class reference to instantiate a new object, which does work, but oddly gave me an error saying I must add a required initializer:
works:
class MyClass {
var count = 0
required init() {
}
}
let myClass2 = MyClass.self
let mc2 = MyClass2()
Still only a small step toward actually discovering the type of any given object though
edit: I've removed a substantial number of now irrelevant details - look at the edit history if you're interested :)
| 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 weight use the first option.
Swift 3 Update:
label.font = label.font.withSize(20)
Swift 4 Update:
label.font = label.font.withSize(20)
or
label.font = UIFont(name:"fontname", size: 20.0)
and if you use the system fonts
label.font = UIFont.systemFont(ofSize: 20.0)
label.font = UIFont.boldSystemFont(ofSize: 20.0)
label.font = UIFont.italicSystemFont(ofSize: 20.0)
| 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"
str.remove(at: str.index(before: str.endIndex)) // "d"
str // "Hello, Worl" (modifying)
Swift 3.0
The APIs have gotten a bit more swifty, and as a result the Foundation extension has changed a bit:
var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name) // "Dolphin"
print(truncated) // "Dolphi"
Or the in-place version:
var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name) // "Dolphi"
Thanks Zmey, Rob Allen!
Swift 2.0+ Way
There are a few ways to accomplish this:
Via the Foundation extension, despite not being part of the Swift library:
var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name) // "Dolphin"
print(truncated) // "Dolphi"
Using the removeRange() method (which alters the name):
var name: String = "Dolphin"
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"
Using the dropLast() function:
var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name) // "Dolphin"
print(truncated) // "Dolphi"
Old String.Index (Xcode 6 Beta 4 +) Way
Since String types in Swift aim to provide excellent UTF-8 support, you can no longer access character indexes/ranges/substrings using Int types. Instead, you use String.Index:
let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"
Alternatively (for a more practical, but less educational example) you can use endIndex:
let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"
Note: I found this to be a great starting point for understanding String.Index
Old (pre-Beta 4) Way
You can simply use the substringToIndex() function, providing it one less than the length of the String:
let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"
| 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.amount = amount
self.includeDecimal = round(amount)-amount > 0
}
}
However, this gives me a compiler error as follows:
Cannot assign value of type 'Binding' to type 'Double'
How do I implement a custom init method which takes in a Binding struct?
| 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 using the property (put self in front of it):
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(amount: Binding<Double>) {
// self.$amount = amount // beta 3
self._amount = amount // beta 4
self.includeDecimal = round(self.amount)-self.amount > 0
}
}
or using .value after (but without self, because you are using the passed parameter, not the struct's property):
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(amount: Binding<Double>) {
// self.$amount = amount // beta 3
self._amount = amount // beta 4
self.includeDecimal = round(amount.value)-amount.value > 0
}
}
This is the same, but we use different names for the parameter (withAmount) and the property (amount), so you clearly see when you are using each.
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(withAmount: Binding<Double>) {
// self.$amount = withAmount // beta 3
self._amount = withAmount // beta 4
self.includeDecimal = round(self.amount)-self.amount > 0
}
}
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(withAmount: Binding<Double>) {
// self.$amount = withAmount // beta 3
self._amount = withAmount // beta 4
self.includeDecimal = round(withAmount.value)-withAmount.value > 0
}
}
Note that .value is not necessary with the property, thanks to the property wrapper (@Binding), which creates the accessors that makes the .value unnecessary. However, with the parameter, there is not such thing and you have to do it explicitly. If you would like to learn more about property wrappers, check the WWDC session 415 - Modern Swift API Design and jump to 23:12.
As you discovered, modifying the @State variable from the initilizer will throw the following error: Thread 1: Fatal error: Accessing State outside View.body. To avoid it, you should either remove the @State. Which makes sense because includeDecimal is not a source of truth. Its value is derived from amount. By removing @State, however, includeDecimal will not update if amount changes. To achieve that, the best option, is to define your includeDecimal as a computed property, so that its value is derived from the source of truth (amount). This way, whenever the amount changes, your includeDecimal does too. If your view depends on includeDecimal, it should update when it changes:
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal: Bool {
return round(amount)-amount > 0
}
init(withAmount: Binding<Double>) {
self.$amount = withAmount
}
var body: some View { ... }
}
As indicated by rob mayoff, you can also use $$varName (beta 3), or _varName (beta4) to initialise a State variable:
// Beta 3:
$$includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0)
// Beta 4:
_includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0)
| 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 dynamically include / exclude code depending on which version / simulator is running, so I'd really be looking for something like a pre-processor directive that can provide me this info.
| 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 iOS framework. On earlier versions of the toolchain, you had to write:
#include "TargetConditionals.h"
but this is no longer necessary on the current (Xcode 6/iOS8) toolchain.
So, for example, if you want to check that you are running on device, you should do
#if TARGET_OS_SIMULATOR
// Simulator-specific code
#else
// Device-specific code
#endif
depending on which is appropriate for your use-case.
| 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 placeholder text colour in a UITextField using Swift?
| 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: "Placeholder Text",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)
Swift 3:
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)
Older Swift:
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSForegroundColorAttributeName: UIColor.white]
)
| 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(???, withString: string)
| 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(with: n1)) // 🇩🇪
// NSRange back to String range:
let r2 = Range(n1, in: str)!
print(str[r2]) // 🇩🇪
Therefore the text replacement in the text field delegate method
can now be done as
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if let oldString = textField.text {
let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
with: string)
// ...
}
// ...
}
(Older answers for Swift 3 and earlier:)
As of Swift 1.2, String.Index has an initializer
init?(_ utf16Index: UTF16Index, within characters: String)
which can be used to convert NSRange to Range<String.Index> correctly
(including all cases of Emojis, Regional Indicators or other extended
grapheme clusters) without intermediate conversion to an NSString:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = advance(utf16.startIndex, nsRange.location, utf16.endIndex)
let to16 = advance(from16, nsRange.length, utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
This method returns an optional string range because not all NSRanges
are valid for a given Swift string.
The UITextFieldDelegate delegate method can then be written as
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let swRange = textField.text.rangeFromNSRange(range) {
let newString = textField.text.stringByReplacingCharactersInRange(swRange, withString: string)
// ...
}
return true
}
The inverse conversion is
extension String {
func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.startIndex, within: utf16view)
let to = String.UTF16View.Index(range.endIndex, within: utf16view)
return NSMakeRange(from - utf16view.startIndex, to - from)
}
}
A simple test:
let str = "a👿b🇩🇪c"
let r1 = str.rangeOfString("🇩🇪")!
// String range to NSRange:
let n1 = str.NSRangeFromRange(r1)
println((str as NSString).substringWithRange(n1)) // 🇩🇪
// NSRange back to String range:
let r2 = str.rangeFromNSRange(n1)!
println(str.substringWithRange(r2)) // 🇩🇪
Update for Swift 2:
The Swift 2 version of rangeFromNSRange() was already given
by Serhii Yakovenko in this answer, I am including it
here for completeness:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
The Swift 2 version of NSRangeFromRange() is
extension String {
func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.startIndex, within: utf16view)
let to = String.UTF16View.Index(range.endIndex, within: utf16view)
return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))
}
}
Update for Swift 3 (Xcode 8):
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
length: utf16.distance(from: from, to: to))
}
}
extension String {
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
let from = from16.samePosition(in: self),
let to = to16.samePosition(in: self)
else { return nil }
return from ..< to
}
}
Example:
let str = "a👿b🇩🇪c"
let r1 = str.range(of: "🇩🇪")!
// String range to NSRange:
let n1 = str.nsRange(from: r1)
print((str as NSString).substring(with: n1)) // 🇩🇪
// NSRange back to String range:
let r2 = str.range(from: n1)!
print(str.substring(with: r2)) // 🇩🇪
| 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 multiple lines:
var text = "This is some text\n"
+ "over multiple lines\n"
| 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
Manually elevating the permissions of the built MyApp.app
Restarting my computer
Has anyone else run into this problem and found a solution?
| 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(""))
{
println("Sign in failed. Empty character")
}
}
My previous code was in Objective-C, which was working fine:
if([[self.username text] isEqualToString: @""] ||
[[self.password text] isEqualToString: @""] ) {
I assume I cannot use isEqualToString in Swift.
| 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.update), userInfo: nil, repeats: true)
// Swift 2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
// Swift <2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}
// must be internal or public.
@objc func update() {
// Something cool
}
For Swift 4, the method of which you want to get the selector must be exposed to Objective-C, thus @objc attribute must be added to the method declaration.
| 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 limit the visibility of data in Swift?
| 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.
However, open access applies only to classes and class members, and it differs from public access as follows:
public classes and class members can only be subclassed and overridden within the defining module (target).
open classes and class members can be subclassed and overridden both within and outside the defining module (target).
// First.framework – A.swift
open class A {}
// First.framework – B.swift
public class B: A {} // ok
// Second.framework – C.swift
import First
internal class C: A {} // ok
// Second.framework – D.swift
import First
internal class D: B {} // error: B cannot be subclassed
2. internal
Enables an entity to be used within the defining module (target). You typically use internal access when defining an app’s or a framework’s internal structure.
// First.framework – A.swift
internal struct A {}
// First.framework – B.swift
A() // ok
// Second.framework – C.swift
import First
A() // error: A is unavailable
3. fileprivate
Restricts the use of an entity to its defining source file. You typically use fileprivate access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
// First.framework – A.swift
internal struct A {
fileprivate static let x: Int
}
A.x // ok
// First.framework – B.swift
A.x // error: x is not available
4. private
Restricts the use of an entity to its enclosing declaration. You typically use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
// First.framework – A.swift
internal struct A {
private static let x: Int
internal static func doSomethingWithX() {
x // ok
}
}
A.x // error: x is unavailable
| 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:
println("zero as a Double")
case let someInt as Int:
println("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
println("a positive double value of \(someDouble)")
// here it comes:
case is Double:
println("some other double value that I don't want to print")
case let someString as String:
println("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
println("an (x, y) point at \(x), \(y)")
case let movie as Movie:
println("a movie called '\(movie.name)', dir. \(movie.director)")
default:
println("something else")
}
}
| 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 titleLabel to set any text for title directly.
| 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 largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
I understand that as the dictionary is being transversed, the largest number is being set to the variable, largest. However, I am confused as to why Xcode is saying that largest is being set 5 times, or 1 time, or 3 times, depending on each test.
When looking through the code, I see that it should be set 6 times in "Prime" alone (2, 3, 5, 7, 11, 13). Then it should skip over any numbers in "Fibonacci" since those are all less than the largest, which is currently set to 13 from "Prime". Then, it should be set to 16, and finally 25 in "Square", yielding a total of 8 times.
Am I missing something entirely obvious?
| 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 element of Square so largest would be set 5 times for the 5 elements in Square and then would stay at 25.
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
println("kind: \(kind)")
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
This prints:
kind: Square
kind: Prime
kind: Fibonacci
| 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 UIUserInterfaceIdiomPad
if ( IDIOM == IPAD ) {
/* do something specifically for iPad. */
} else {
/* do something specifically for iPhone or iPod touch. */
}
Other Examples
if ( [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPad"] ) {
return YES; /* Device is iPad */
}
#define IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
if ( IPAD )
return YES;
For a Swift solution, see this answer: https://stackoverflow.com/a/27517536/2057171
| 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 native Swift way is that the dictionary uses generic types, so if you define it with Int as the key and String as the value, you cannot mistakenly use keys and values of different types. (The compiler checks the types on your behalf.)
Based on what I see in your code, your dictionary uses Int as the key and String as the value. To create an instance and add an item at a later time you can use this code:
var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"
If you later need to assign it to a variable of NSDictionary type, just do an explicit cast:
let nsDict = dict as! NSDictionary
And, as mentioned earlier, if you want to pass it to a function expecting NSDictionary, pass it as-is without any cast or conversion.
| 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"
return String((0..<length).map{ _ in letters.randomElement()! })
}
Swift 3.0 Update
func randomString(length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
Original answer:
func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString : NSMutableString = NSMutableString(capacity: len)
for (var i=0; i < len; i++){
var length = UInt32 (letters.length)
var rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
return randomString
}
| 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 replaces the typed word is all lowercase. So I need to apply .uppercaseString to only the first letter. I originally thought I could use
nameOfString[0]
but this apparently does not work. How can I get the first letter of the string to uppercase, and then be able to print the full string with the first letter capitalized?
Thanks for any help!
| 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
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
Swift 4:
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + self.lowercased().dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
| 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 optional.
Why would you want to use an optional value?
| 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 of what they are. Compare the optional above to creating a normal String:
var name: String = "Bertie" // No "?" after String
From the syntax it looks like an optional String is very similar to an ordinary String. It's not. An optional String is not a String with some "optional" setting turned on. It's not a special variety of String. A String and an optional String are completely different types.
Here's the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int. Think of an optional as a kind of parcel. Before you open it (or "unwrap" in the language of optionals) you won't know if it contains something or nothing.
You can see how optionals are implemented in the Swift Standard Library by typing "Optional" into any Swift file and ⌘-clicking on it. Here's the important part of the definition:
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
Optional is just an enum which can be one of two cases: .none or .some. If it's .some, there's an associated value which, in the example above, would be the String "Hello". An optional uses Generics to give a type to the associated value. The type of an optional String isn't String, it's Optional, or more precisely Optional<String>.
Everything Swift does with optionals is magic to make reading and writing code more fluent. Unfortunately this obscures the way it actually works. I'll go through some of the tricks later.
Note: I'll be talking about optional variables a lot, but it's fine to create optional constants too. I mark all variables with their type to make it easier to understand type types being created, but you don't have to in your own code.
How to create optionals
To create an optional, append a ? after the type you wish to wrap. Any type can be optional, even your own custom types. You can't have a space between the type and the ?.
var name: String? = "Bob" // Create an optional String that contains "Bob"
var peter: Person? = Person() // An optional "Person" (custom type)
// A class with a String and an optional String property
class Car {
var modelName: String // must exist
var internalName: String? // may or may not exist
}
Using optionals
You can compare an optional to nil to see if it has a value:
var name: String? = "Bob"
name = nil // Set name to nil, the absence of a value
if name != nil {
print("There is a name")
}
if name == nil { // Could also use an "else"
print("Name has no value")
}
This is a little confusing. It implies that an optional is either one thing or another. It's either nil or it's "Bob". This is not true, the optional doesn't transform into something else. Comparing it to nil is a trick to make easier-to-read code. If an optional equals nil, this just means that the enum is currently set to .none.
Only optionals can be nil
If you try to set a non-optional variable to nil, you'll get an error.
var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'
Another way of looking at optionals is as a complement to normal Swift variables. They are a counterpart to a variable which is guaranteed to have a value. Swift is a careful language that hates ambiguity. Most variables are define as non-optionals, but sometimes this isn't possible. For example, imagine a view controller which loads an image either from a cache or from the network. It may or may not have that image at the time the view controller is created. There's no way to guarantee the value for the image variable. In this case you would have to make it optional. It starts as nil and when the image is retrieved, the optional gets a value.
Using an optional reveals the programmers intent. Compared to Objective-C, where any object could be nil, Swift needs you to be clear about when a value can be missing and when it's guaranteed to exist.
To use an optional, you "unwrap" it
An optional String cannot be used in place of an actual String. To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a ! after the optional name. This is called "force unwrapping". It returns the value inside the optional (as the original type) but if the optional is nil, it causes a runtime crash. Before unwrapping you should be sure there's a value.
var name: String? = "Bob"
let unwrappedName: String = name!
print("Unwrapped name: \(unwrappedName)")
name = nil
let nilName: String = name! // Runtime crash. Unexpected nil.
Checking and using an optional
Because you should always check for nil before unwrapping and using an optional, this is a common pattern:
var mealPreference: String? = "Vegetarian"
if mealPreference != nil {
let unwrappedMealPreference: String = mealPreference!
print("Meal: \(unwrappedMealPreference)") // or do something useful
}
In this pattern you check that a value is present, then when you are sure it is, you force unwrap it into a temporary constant to use. Because this is such a common thing to do, Swift offers a shortcut using "if let". This is called "optional binding".
var mealPreference: String? = "Vegetarian"
if let unwrappedMealPreference: String = mealPreference {
print("Meal: \(unwrappedMealPreference)")
}
This creates a temporary constant (or variable if you replace let with var) whose scope is only within the if's braces. Because having to use a name like "unwrappedMealPreference" or "realMealPreference" is a burden, Swift allows you to reuse the original variable name, creating a temporary one within the bracket scope
var mealPreference: String? = "Vegetarian"
if let mealPreference: String = mealPreference {
print("Meal: \(mealPreference)") // separate from the other mealPreference
}
Here's some code to demonstrate that a different variable is used:
var mealPreference: String? = "Vegetarian"
if var mealPreference: String = mealPreference {
print("Meal: \(mealPreference)") // mealPreference is a String, not a String?
mealPreference = "Beef" // No effect on original
}
// This is the original mealPreference
print("Meal: \(mealPreference)") // Prints "Meal: Optional("Vegetarian")"
Optional binding works by checking to see if the optional equals nil. If it doesn't, it unwraps the optional into the provided constant and executes the block. In Xcode 8.3 and later (Swift 3.1), trying to print an optional like this will cause a useless warning. Use the optional's debugDescription to silence it:
print("\(mealPreference.debugDescription)")
What are optionals for?
Optionals have two use cases:
Things that can fail (I was expecting something but I got nothing)
Things that are nothing now but might be something later (and vice-versa)
Some concrete examples:
A property which can be there or not there, like middleName or spouse in a Person class
A method which can return a value or nothing, like searching for a match in an array
A method which can return either a result or get an error and return nothing, like trying to read a file's contents (which normally returns the file's data) but the file doesn't exist
Delegate properties, which don't always have to be set and are generally set after initialization
For weak properties in classes. The thing they point to can be set to nil at any time
A large resource that might have to be released to reclaim memory
When you need a way to know when a value has been set (data not yet loaded > the data) instead of using a separate dataLoaded Boolean
Optionals don't exist in Objective-C but there is an equivalent concept, returning nil. Methods that can return an object can return nil instead. This is taken to mean "the absence of a valid object" and is often used to say that something went wrong. It only works with Objective-C objects, not with primitives or basic C-types (enums, structs). Objective-C often had specialized types to represent the absence of these values (NSNotFound which is really NSIntegerMax, kCLLocationCoordinate2DInvalid to represent an invalid coordinate, -1 or some negative value are also used). The coder has to know about these special values so they must be documented and learned for each case. If a method can't take nil as a parameter, this has to be documented. In Objective-C, nil was a pointer just as all objects were defined as pointers, but nil pointed to a specific (zero) address. In Swift, nil is a literal which means the absence of a certain type.
Comparing to nil
You used to be able to use any optional as a Boolean:
let leatherTrim: CarExtras? = nil
if leatherTrim {
price = price + 1000
}
In more recent versions of Swift you have to use leatherTrim != nil. Why is this? The problem is that a Boolean can be wrapped in an optional. If you have Boolean like this:
var ambiguous: Boolean? = false
it has two kinds of "false", one where there is no value and one where it has a value but the value is false. Swift hates ambiguity so now you must always check an optional against nil.
You might wonder what the point of an optional Boolean is? As with other optionals the .none state could indicate that the value is as-yet unknown. There might be something on the other end of a network call which takes some time to poll. Optional Booleans are also called "Three-Value Booleans"
Swift tricks
Swift uses some tricks to allow optionals to work. Consider these three lines of ordinary looking optional code;
var religiousAffiliation: String? = "Rastafarian"
religiousAffiliation = nil
if religiousAffiliation != nil { ... }
None of these lines should compile.
The first line sets an optional String using a String literal, two different types. Even if this was a String the types are different
The second line sets an optional String to nil, two different types
The third line compares an optional string to nil, two different types
I'll go through some of the implementation details of optionals that allow these lines to work.
Creating an optional
Using ? to create an optional is syntactic sugar, enabled by the Swift compiler. If you want to do it the long way, you can create an optional like this:
var name: Optional<String> = Optional("Bob")
This calls Optional's first initializer, public init(_ some: Wrapped), which infers the optional's associated type from the type used within the parentheses.
The even longer way of creating and setting an optional:
var serialNumber:String? = Optional.none
serialNumber = Optional.some("1234")
print("\(serialNumber.debugDescription)")
Setting an optional to nil
You can create an optional with no initial value, or create one with the initial value of nil (both have the same outcome).
var name: String?
var name: String? = nil
Allowing optionals to equal nil is enabled by the protocol ExpressibleByNilLiteral (previously named NilLiteralConvertible). The optional is created with Optional's second initializer, public init(nilLiteral: ()). The docs say that you shouldn't use ExpressibleByNilLiteral for anything except optionals, since that would change the meaning of nil in your code, but it's possible to do it:
class Clint: ExpressibleByNilLiteral {
var name: String?
required init(nilLiteral: ()) {
name = "The Man with No Name"
}
}
let clint: Clint = nil // Would normally give an error
print("\(clint.name)")
The same protocol allows you to set an already-created optional to nil. Although it's not recommended, you can use the nil literal initializer directly:
var name: Optional<String> = Optional(nilLiteral: ())
Comparing an optional to nil
Optionals define two special "==" and "!=" operators, which you can see in the Optional definition. The first == allows you to check if any optional is equal to nil. Two different optionals which are set to .none will always be equal if the associated types are the same. When you compare to nil, behind the scenes Swift creates an optional of the same associated type, set to .none then uses that for the comparison.
// How Swift actually compares to nil
var tuxedoRequired: String? = nil
let temp: Optional<String> = Optional.none
if tuxedoRequired == temp { // equivalent to if tuxedoRequired == nil
print("tuxedoRequired is nil")
}
The second == operator allows you to compare two optionals. Both have to be the same type and that type needs to conform to Equatable (the protocol which allows comparing things with the regular "==" operator). Swift (presumably) unwraps the two values and compares them directly. It also handles the case where one or both of the optionals are .none. Note the distinction between comparing to the nil literal.
Furthermore, it allows you to compare any Equatable type to an optional wrapping that type:
let numberToFind: Int = 23
let numberFromString: Int? = Int("23") // Optional(23)
if numberToFind == numberFromString {
print("It's a match!") // Prints "It's a match!"
}
Behind the scenes, Swift wraps the non-optional as an optional before the comparison. It works with literals too (if 23 == numberFromString {)
I said there are two == operators, but there's actually a third which allow you to put nil on the left-hand side of the comparison
if nil == name { ... }
Naming Optionals
There is no Swift convention for naming optional types differently from non-optional types. People avoid adding something to the name to show that it's an optional (like "optionalMiddleName", or "possibleNumberAsString") and let the declaration show that it's an optional type. This gets difficult when you want to name something to hold the value from an optional. The name "middleName" implies that it's a String type, so when you extract the String value from it, you can often end up with names like "actualMiddleName" or "unwrappedMiddleName" or "realMiddleName". Use optional binding and reuse the variable name to get around this.
The official definition
From "The Basics" in the Swift Programming Language:
Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.
Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.
To finish, here's a poem from 1899 about optionals:
Yesterday upon the stair
I met a man who wasn’t there
He wasn’t there again today
I wish, I wish he’d go away
Antigonish
More resources:
The Swift Programming Guide
Optionals in Swift (Medium)
WWDC Session 402 "Introduction to Swift" (starts around 14:15)
More optional tips and tricks
| 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.shared.keyWindow
let topPadding = window?.safeAreaInsets.top
let bottomPadding = window?.safeAreaInsets.bottom
}
In Swift - iOS 13.0+
// Use the first element from windows array as KeyWindow deprecated
if #available(iOS 13.0, *) {
let window = UIApplication.shared.windows.first
let topPadding = window.safeAreaInsets.top
let bottomPadding = window.safeAreaInsets.bottom
}
In Swift - iOS 15.0+
// Use the keyWindow of the currentScene
if #available(iOS 15.0, *) {
let window = UIApplication.shared.currentScene?.keyWindow
let topPadding = window.safeAreaInsets.top
let bottomPadding = window.safeAreaInsets.bottom
}
| 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.
How can I read information from sysData?
| 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 #available(iOS 9.0, *) {
// use the feature only available in iOS 9
// for ex. UIStackView
} else {
// or use some work around
}
BUT it is not recommended to check the OS version. It is better to check if the feature you want to use is available on the device than comparing version numbers.
For iOS, as mentioned above, you should check if it responds to a selector;
eg.:
if (self.respondsToSelector(Selector("showViewController"))) {
self.showViewController(vc, sender: self)
} else {
// some work around
}
| 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 your project.
Delete the Derived Data folder (Go to Xcode > Preferences > Locations and click the gray arrow by the Derived Data folder. Then delete your project folder.)
Click delete on the class, remove reference (not Move to Trash), and add it back again. (see this answer)
| 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 screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
Unfortunately, I am unsure of how to convert this to Swift. Does anyone have an idea?
Thanks!
| 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 screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift:
Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
| 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_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
It results in this interface:
How can I make the VStack fill the width of the screen even if the labels/text components don't need the full width?
A trick I've found is to insert an empty HStack in the structure like so:
VStack(alignment: .leading) {
HStack {
Spacer()
}
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
Spacer()
}
Which yields the desired design:
Is there a better way?
| 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(.title)
Text("Another")
.font(.body)
Spacer()
}
.frame(
minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity,
alignment: .topLeading
)
.background(Color.red)
}
}
This is described as being a flexible frame (see the documentation), which will stretch to fill the whole screen, and when it has extra space it will center its contents inside of it.
| 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 SomeClass {
var someProperty: AnyObject {
didSet {
doStuff()
}
}
init(someProperty: AnyObject) {
self.someProperty = someProperty
doStuff()
}
func doStuff() {
// do stuff now that someProperty is set
}
}
I created the method doStuff, to make the processing calls more concise, but I'd rather just process the property within the didSet function. Is there a way to force this to call during initialization?
Update
I decided to just remove the convenience intializer for my class and force you to set the property after initialization. This allows me to know didSet will always be called. I haven't decided if this is better overall, but it suits my situation well.
| 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 methods that you have to keep track of calling in the right places.
For example:
public class MyNewType: NSObject {
public var myRequiredField:Int
public var myOptionalField:Float? {
willSet {
if let newValue = newValue {
print("I'm going to change to \(newValue)")
}
}
didSet {
if let myOptionalField = self.myOptionalField {
print("Now I'm \(myOptionalField)")
}
}
}
override public init() {
self.myRequiredField = 1
super.init()
// Non-defered
self.myOptionalField = 6.28
// Defered
defer {
self.myOptionalField = 3.14
}
}
}
Will yield:
I'm going to change to 3.14
Now I'm 3.14
| 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 slightly rounded button with no background, only a 1pt border of a certain color.
| 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 what it suggests:
return str.substringWithRange(aRange: Range<String.Index>)
I haven't found anything in the Swift Standard Reference Library that helps. Here was another wild guess:
return str.substringWithRange(Range(0, 1))
And this:
let r:Range<String.Index> = Range<String.Index>(start: 0, end: 2)
return str.substringWithRange(r)
I've seen other answers (Finding index of character in Swift String) that seem to suggest that since String is a bridge type for NSString, the "old" methods should work, but it's not clear how - e.g., this doesn't work either (doesn't appear to be valid syntax):
let x = str.substringWithRange(NSMakeRange(0, 3))
Thoughts?
| 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.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(2), end: str.endIndex.advancedBy(-1))) //"llo, playgroun"
You can also still use the NSString method with NSRange, but you have to make sure you are using an NSString like this:
let myNSString = str as NSString
myNSString.substringWithRange(NSRange(location: 0, length: 3))
Note: as JanX2 mentioned, this second method is not safe with unicode strings.
| 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];
NSString *base64String = [self encodeBase64:imageData];
| 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 = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!
Swift 2.0 > Encoding
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
Swift 2.0 > Decoding
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!
Swift 3.0 > Decoding
let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
Encoding :
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)
Decoding :
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage
Swift 3.0
let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImageView.image = decodedimage
Objective-C
iOS7 > version
You can use NSData's base64EncodedStringWithOptions
Encoding :
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
Decoding :
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
iOS 6.1 and < version
First Option : Use this link to encode and decode image
Add Base64 class in your project.
Encoding :
NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
NSString *strEncoded = [Base64 encode:data];
Decoding :
NSData* data = [Base64 decode:strEncoded ];;
image.image = [UIImage imageWithData:data];
Another Option: Use QSUtilities for encoding and decoding
| 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 app you want do add the purchase to
Click the Features header, and then select In-App Purchases on the left
Click the + icon in the middle
For this tutorial, we are going to be adding an in-app purchase to remove ads, so choose non-consumable. If you were going to send a physical item to the user, or give them something that they can buy more than once, you would choose consumable.
For the reference name, put whatever you want (but make sure you know what it is)
For product id put tld.websitename.appname.referencename this will work the best, so for example, you could use com.jojodmo.blix.removeads
Choose cleared for sale and then choose price tier as 1 (99¢). Tier 2 would be $1.99, and tier 3 would be $2.99. The full list is available if you click view pricing matrix I recommend you use tier 1, because that's usually the most anyone will ever pay to remove ads.
Click the blue add language button, and input the information. This will ALL be shown to the customer, so don't put anything you don't want them seeing
For hosting content with Apple choose no
You can leave the review notes blank FOR NOW.
Skip the screenshot for review FOR NOW, everything we skip we will come back to.
Click 'save'
It could take a few hours for your product ID to register in App Store Connect, so be patient.
Setting up your project
Now that you've set up your in-app purchase information on App Store Connect, go into your Xcode project, and go to the application manager (blue page-like icon at the top of where your methods and header files are) click on your app under targets (should be the first one) then go to general. At the bottom, you should see linked frameworks and libraries click the little plus symbol and add the framework StoreKit.framework If you don't do this, the in-app purchase will NOT work!
If you are using Objective-C as the language for your app, you should skip these five steps. Otherwise, if you are using Swift, you can follow My Swift Answer for this question, here, or, if you prefer to use Objective-C for the In-App Purchase code but are using Swift in your app, you can do the following:
Create a new .h (header) file by going to File > New > File... (Command ⌘ + N). This file will be referred to as "Your .h file" in the rest of the tutorial
When prompted, click Create Bridging Header. This will be our bridging header file. If you are not prompted, go to step 3. If you are prompted, skip step 3 and go directly to step 4.
Create another .h file named Bridge.h in the main project folder, Then go to the Application Manager (the blue page-like icon), then select your app in the Targets section, and click Build Settings. Find the option that says Swift Compiler - Code Generation, and then set the Objective-C Bridging Header option to Bridge.h
In your bridging header file, add the line #import "MyObjectiveCHeaderFile.h", where MyObjectiveCHeaderFile is the name of the header file that you created in step one. So, for example, if you named your header file InAppPurchase.h, you would add the line #import "InAppPurchase.h" to your bridge header file.
Create a new Objective-C Methods (.m) file by going to File > New > File... (Command ⌘ + N). Name it the same as the header file you created in step 1. For example, if you called the file in step 1 InAppPurchase.h, you would call this new file InAppPurchase.m. This file will be referred to as "Your .m file" in the rest of the tutorial.
Coding
Now we're going to get into the actual coding. Add the following code into your .h file:
BOOL areAdsRemoved;
- (IBAction)restore;
- (IBAction)tapsRemoveAds;
Next, you need to import the StoreKit framework into your .m file, as well as add SKProductsRequestDelegate and SKPaymentTransactionObserver after your @interface declaration:
#import <StoreKit/StoreKit.h>
//put the name of your view controller in place of MyViewController
@interface MyViewController() <SKProductsRequestDelegate, SKPaymentTransactionObserver>
@end
@implementation MyViewController //the name of your view controller (same as above)
//the code below will be added here
@end
and now add the following into your .m file, this part gets complicated, so I suggest that you read the comments in the code:
//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product
#define kRemoveAdsProductIdentifier @"put your product id (the one that we just made in App Store Connect) in here"
- (IBAction)tapsRemoveAds{
NSLog(@"User requests to remove ads");
if([SKPaymentQueue canMakePayments]){
NSLog(@"User can make payments");
//If you have more than one in-app purchase, and would like
//to have the user purchase a different product, simply define
//another function and replace kRemoveAdsProductIdentifier with
//the identifier for the other product
SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kRemoveAdsProductIdentifier]];
productsRequest.delegate = self;
[productsRequest start];
}
else{
NSLog(@"User cannot make payments due to parental controls");
//this is called the user cannot make payments, most likely due to parental controls
}
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
SKProduct *validProduct = nil;
int count = [response.products count];
if(count > 0){
validProduct = [response.products objectAtIndex:0];
NSLog(@"Products Available!");
[self purchase:validProduct];
}
else if(!validProduct){
NSLog(@"No products available");
//this is called if your product id is not valid, this shouldn't be called unless that happens.
}
}
- (void)purchase:(SKProduct *)product{
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (IBAction) restore{
//this is called when the user restores purchases, you should hook this up to a button
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
NSLog(@"received restored transactions: %i", queue.transactions.count);
for(SKPaymentTransaction *transaction in queue.transactions){
if(transaction.transactionState == SKPaymentTransactionStateRestored){
//called when the user successfully restores a purchase
NSLog(@"Transaction state -> Restored");
//if you have more than one in-app purchase product,
//you restore the correct product for the identifier.
//For example, you could use
//if(productID == kRemoveAdsProductIdentifier)
//to get the product identifier for the
//restored purchases, you can use
//
//NSString *productID = transaction.payment.productIdentifier;
[self doRemoveAds];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
}
}
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
for(SKPaymentTransaction *transaction in transactions){
//if you have multiple in app purchases in your app,
//you can get the product identifier of this transaction
//by using transaction.payment.productIdentifier
//
//then, check the identifier against the product IDs
//that you have defined to check which product the user
//just purchased
switch(transaction.transactionState){
case SKPaymentTransactionStatePurchasing: NSLog(@"Transaction state -> Purchasing");
//called when the user is in the process of purchasing, do not add any of your own code here.
break;
case SKPaymentTransactionStatePurchased:
//this is called when the user has successfully purchased the package (Cha-Ching!)
[self doRemoveAds]; //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
NSLog(@"Transaction state -> Purchased");
break;
case SKPaymentTransactionStateRestored:
NSLog(@"Transaction state -> Restored");
//add the same code as you did from SKPaymentTransactionStatePurchased here
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
//called when the transaction does not finish
if(transaction.error.code == SKErrorPaymentCancelled){
NSLog(@"Transaction state -> Cancelled");
//the user cancelled the payment ;(
}
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
}
}
}
Now you want to add your code for what will happen when the user finishes the transaction, for this tutorial, we use removing adds, you will have to add your own code for what happens when the banner view loads.
- (void)doRemoveAds{
ADBannerView *banner;
[banner setAlpha:0];
areAdsRemoved = YES;
removeAdsButton.hidden = YES;
removeAdsButton.enabled = NO;
[[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];
//use NSUserDefaults so that you can load whether or not they bought it
//it would be better to use KeyChain access, or something more secure
//to store the user data, because NSUserDefaults can be changed.
//You're average downloader won't be able to change it very easily, but
//it's still best to use something more secure than NSUserDefaults.
//For the purpose of this tutorial, though, we're going to use NSUserDefaults
[[NSUserDefaults standardUserDefaults] synchronize];
}
If you don't have ads in your application, you can use any other thing that you want. For example, we could make the color of the background blue. To do this we would want to use:
- (void)doRemoveAds{
[self.view setBackgroundColor:[UIColor blueColor]];
areAdsRemoved = YES
//set the bool for whether or not they purchased it to YES, you could use your own boolean here, but you would have to declare it in your .h file
[[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];
//use NSUserDefaults so that you can load wether or not they bought it
[[NSUserDefaults standardUserDefaults] synchronize];
}
Now, somewhere in your viewDidLoad method, you're going to want to add the following code:
areAdsRemoved = [[NSUserDefaults standardUserDefaults] boolForKey:@"areAdsRemoved"];
[[NSUserDefaults standardUserDefaults] synchronize];
//this will load wether or not they bought the in-app purchase
if(areAdsRemoved){
[self.view setBackgroundColor:[UIColor blueColor]];
//if they did buy it, set the background to blue, if your using the code above to set the background to blue, if your removing ads, your going to have to make your own code here
}
Now that you have added all the code, go into your .xib or storyboard file, and add two buttons, one saying purchase, and the other saying restore. Hook up the tapsRemoveAds IBAction to the purchase button that you just made, and the restore IBAction to the restore button. The restore action will check if the user has previously purchased the in-app purchase, and give them the in-app purchase for free if they do not already have it.
Submitting for review
Next, go into App Store Connect, and click Users and Access then click the Sandbox Testers header, and then click the + symbol on the left where it says Testers. You can just put in random things for the first and last name, and the e-mail does not have to be real - you just have to be able to remember it. Put in a password (which you will have to remember) and fill in the rest of the info. I would recommend that you make the Date of Birth a date that would make the user 18 or older. App Store Territory HAS to be in the correct country. Next, log out of your existing iTunes account (you can log back in after this tutorial).
Now, run your application on your iOS device, if you try running it on the simulator, the purchase will always error, you HAVE TO run it on your iOS device. Once the app is running, tap the purchase button. When you are prompted to log into your iTunes account, log in as the test user that we just created. Next,when it asks you to confirm the purchase of 99¢ or whatever you set the price tier too, TAKE A SCREEN SNAPSHOT OF IT this is what your going to use for your screenshot for review on App Store Connect. Now cancel the payment.
Now, go to App Store Connect, then go to My Apps > the app you have the In-app purchase on > In-App Purchases. Then click your in-app purchase and click edit under the in-app purchase details. Once you've done that, import the photo that you just took on your iPhone into your computer, and upload that as the screenshot for review, then, in review notes, put your TEST USER e-mail and password. This will help apple in the review process.
After you have done this, go back onto the application on your iOS device, still logged in as the test user account, and click the purchase button. This time, confirm the payment Don't worry, this will NOT charge your account ANY money, test user accounts get all in-app purchases for free After you have confirmed the payment, make sure that what happens when the user buys your product actually happens. If it doesn't, then thats going to be an error with your doRemoveAds method. Again, I recommend using changing the background to blue for testing the in-app purchase, this should not be your actual in-app purchase though. If everything works and you're good to go! Just make sure to include the in-app purchase in your new binary when you upload it to App Store Connect!
Here are some common errors:
Logged: No Products Available
This could mean four things:
You didn't put the correct in-app purchase ID in your code (for the identifier kRemoveAdsProductIdentifier in the above code
You didn't clear your in-app purchase for sale on App Store Connect
You didn't wait for the in-app purchase ID to be registered in App Store Connect. Wait a couple hours from creating the ID, and your problem should be resolved.
You didn't complete filling your Agreements, Tax, and Banking info.
If it doesn't work the first time, don't get frustrated! Don't give up! It took me about 5 hours straight before I could get this working, and about 10 hours searching for the right code! If you use the code above exactly, it should work fine. Feel free to comment if you have any questions at all.
| 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 UIMainStoryboardFile 'MainStoryboard' - perhaps the designated entry point is not set?
And you'll notice that your window property in the app delegate is now nil.
In the app's setting, go to your target and the Info tab. There clear the value of Main storyboard file base name. On the General tab, clear the value for Main Interface. This will remove the warning.
Create the window and desired initial view controller in the app delegate's application:didFinishLaunchingWithOptions: method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
return YES;
}
| 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 safe. If the count you pass to prefix is larger than the array count then it just returns the whole array.
NOTE: as pointed out in the comments, Array.prefix actually returns an ArraySlice, not an Array.
If you need to assign the result to an Array type or pass it to a method that's expecting an Array param, you will need to force the result into an Array type: let first5 = Array(array.prefix(5))
| 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 property is true, it means the View Controller is disappearing because it's being removed (popped).
Should look something like:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingFromParentViewController {
// Your code...
}
}
In swift 4.2
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingFromParent {
// Your code...
}
}
| 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 true, rather than opinions about which is "best")
To get started, my initial impression from reading their ReadMe's is:
As someone who is familiar with the "real" C# Rx from microsoft, RxSwift looks a lot more recognisable.
ReactiveCococa seems to have gone off into its own space now, introducing new abstractions such as Signals vs SignalProducers and Lifting. On the one hand this seems to clarify some situations (what's a Hot vs Cold signal) but on the other hand this seems to increase the complexity of the framework a LOT
| 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 is a framework that shares some things with Rx, but has names with origins in FRP.
The first thing to say is that neither RAC nor RxSwift are Functional Reactive Programming implementations, according to Conal's definition of the concept. From this point everything can be reduced to how each framework handles side effects and a few other components.
Let's talk about the community and meta-tech stuff:
RAC is a 3 years old project, born in Objective-C later ported to Swift (with bridges) for the 3.0 release, after completely dropping the ongoing work on Objective-C.
RxSwift is a few months old project and seems to have a momentum in the community right now. One thing that is important for RxSwift is that is under the ReactiveX organization and that all other implementations are working in the same way, learning how to deal with RxSwift will make working with Rx.Net, RxJava or RxJS a simple task and just a matter of language syntax. I could say that is based on the philosophy learn once, apply everywhere.
Now it's time for the tech stuff.
Producing/Observing Entities
RAC 3.0 has 2 main entities, Signal and SignalProducer, the first one publishes events regardless a subscriber is attached or not, the second one requires a start to actually having signals/events produced. This design has been created to separate the tedious concept of hot and cold observables, that has been source of confusion for a lot of developers. This is why the differences can be reduced to how they manage side effects.
In RxSwift, Signal and SignalProducer translates to Observable, it could sound confusing, but these 2 entities are actually the same thing in the Rx world. A design with Observables in RxSwift has to be created considering if they are hot or cold, it could sound as unnecessary complexity, but once you understood how they work (and again hot/cold/warm is just about the side effects while subscribing/observing) they can be tamed.
In both worlds, the concept of subscription is basically the same, there's one little difference that RAC introduced and is the interruption event when a Signal is disposed before the completion event has been sent.
To recap both have the following kind of events:
Next, to compute the new received value
Error, to compute an error and complete the stream, unsubscribing all the observers
Complete, to mark the stream as completed unsubscribing all observers
RAC in addition has interrupted that is sent when a Signal is disposed before completing either correctly or with an error.
Manually Writing
In RAC, Signal/SignalProducer are read-only entities, they can't be managed from outside, same thing is for Observable in RxSwift. To turn a Signal/SignalProducer into a write-able entity, you have to use the pipe() function to return a manually controlled item. On the Rx space, this is a different type called Subject.
If the read/write concept sounds unfamiliar, a nice analogy with Future/Promise can be made. A Future is a read-only placeholder, like Signal/SignalProducer and Observable, on the other hand, a Promise can be fulfilled manually, like for pipe() and Subject.
Schedulers
This entity is pretty much similar in both worlds, same concepts, but RAC is serial-only, instead RxSwift features also concurrent schedulers.
Composition
Composition is the key feature of Reactive Programming. Composing streams is the essence of both frameworks, in RxSwift they are also called sequences.
All the observable entities in RxSwift are of type ObservableType, so we compose instances of Subject and Observable with the same operators, without any extra concern.
On RAC space, Signal and SignalProducer are 2 different entities and we have to lift on SignalProducer to be able to compose what is produced with instances of Signal. The two entities have their own operators, so when you need to mix things, you have to make sure a certain operator is available, on the other side you forget about the hot/cold observables.
About this part, Colin Eberhardt summed it nicely:
Looking at the current API the signal operations are mainly focussed on the ‘next’ event, allowing you to transform values, skip, delay, combine and observe on different threads. Whereas the signal producer API is mostly concerned with the signal lifecycle events (completed, error), with operations including then, flatMap, takeUntil and catch.
Extra
RAC has also the concept of Action and Property, the former is a type to compute side effects, mainly relating to user interaction, the latter is interesting when observing a value to perform a task when the value has changed. In RxSwift the Action translates again into an Observable, this is nicely shown in RxCocoa, an integration of Rx primitives for both iOS and Mac. The RAC's Property can be translated into Variable (or BehaviourSubject) in RxSwift.
It's important to understand that Property/Variable is the way we have to bridge the imperative world to the declarative nature of Reactive Programming, so sometimes is a fundamental component when dealing with third party libraries or core functionalities of the iOS/Mac space.
Conclusion
RAC and RxSwift are 2 complete different beasts, the former has a long history in the Cocoa space and a lot of contributors, the latter is fairly young, but relies on concepts that have been proven to be effective in other languages like Java, JS or .NET. The decision on which is better is on preference. RAC states that the separation of hot/cold observable was necessary and that is the core feature of the framework, RxSwift says that the unification of them is better than the separation, again it's just about how side effects are managed/performed.
RAC 3.0 seems to have introduced some unexpected complexity on top of the major goal of separating hot/cold observables, like the concept of interruption, splitting operators between 2 entities and introducing some imperative behaviour like start to begin producing signals. For some people these things can be a nice thing to have or even a killer feature, for some others they can be just unnecessary or even dangerous. Another thing to remember is that RAC is trying to keep up with Cocoa conventions as much as possible, so if you are an experienced Cocoa Dev, you should feel more comfortable to work with it rather than RxSwift.
RxSwift on the other hand lives with all the downsides like hot/cold observables, but also the good things, of Reactive Extensions. Moving from RxJS, RxJava or Rx.Net to RxSwift is a simple thing, all the concepts are the same, so this makes finding material pretty interesting, maybe the same problem you are facing now, has been solved by someone in RxJava and the solution can be reapplied taking in consideration the platform.
Which one has to be picked is definitely a matter of preference, from an objective perspective is impossible to tell which one is better. The only way is to fire Xcode and try both of them and pick the one that feels more comfortable to work with. They are 2 implementations of similar concepts, trying to achieve the same goal: simplifying software development.
| 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, but can't find the relevant areas in the code example they supply.
| 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 might want to first check hasStrings, "to avoid causing the system to needlessly attempt to fetch data before it is needed or when the data might not be present", such as when using Handoff.)
| 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 short about them: optional types offer memory safety (this works beautifully with Swift's constructor rules - which are strict in order to provide this benefit).
A weak reference allows the possibility of it to become nil (this happens automatically when the referenced object is deallocated), therefore the type of your property must be optional - so you, as a programmer, are obligated to check it before you use it (basically the compiler forces you, as much as it can, to write safe code).
An unowned reference presumes that it will never become nil during its lifetime. An unowned reference must be set during initialization - this means that the reference will be defined as a non-optional type that can be used safely without checks. If somehow the object being referred to is deallocated, then the app will crash when the unowned reference is used.
From the Apple docs:
Use a weak reference whenever it is valid for that reference to become
nil at some point during its lifetime. Conversely, use an unowned
reference when you know that the reference will never be nil once it
has been set during initialization.
In the docs, there are some examples that discuss retain cycles and how to break them. All these examples are extracted from the docs.
Example of the weak keyword:
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
}
class Apartment {
let number: Int
init(number: Int) { self.number = number }
weak var tenant: Person?
}
And now, for some ASCII art (you should go see the docs - they have pretty diagrams):
Person ===(strong)==> Apartment
Person <==(weak)===== Apartment
The Person and Apartment example shows a situation where two properties, both of which are allowed to be nil, have the potential to cause a strong reference cycle. This scenario is best resolved with a weak reference. Both entities can exist without having a strict dependency upon the other.
Example of the unowned keyword:
class Customer {
let name: String
var card: CreditCard?
init(name: String) { self.name = name }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) { self.number = number; self.customer = customer }
}
In this example, a Customer may or may not have a CreditCard, but a CreditCard will always be associated with a Customer. To represent this, the Customer class has an optional card property, but the CreditCard class has a non-optional (and unowned) customer property.
Customer ===(strong)==> CreditCard
Customer <==(unowned)== CreditCard
The Customer and CreditCard example shows a situation where one property that is allowed to be nil and another property that cannot be nil has the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.
Note from Apple:
Weak references must be declared as variables, to indicate that their
value can change at runtime. A weak reference cannot be declared as a
constant.
There is also a third scenario when both properties should always have a value, and neither property should ever be nil once initialization is complete.
And there are also the classic retain cycle scenarios to avoid when working with closures.
For this, I encourage you to visit the Apple docs, or read the book.
| 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 release];
Swift 4.2 :
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
| 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
dispatch_async(dispatch_get_main_queue()) {
self.imageView.image = image
}
}
Or stuff like this to delay execution:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
print("test")
}
Or any of all kinds of other uses of the Grand Central Dispatch API...
Now that I've opened my project in Xcode 8 (beta) for Swift 3, I get all kinds of errors. Some of them offer to fix my code, but not all of the fixes produce working code. What do I do about this?
| 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 work with it -- act more like Swift-native APIs. The data types import as Swift classes, their related global functions import as methods and properties on those classes, and some related things like sets of constants can become subtypes where appropriate.
In Xcode 8 / Swift 3 beta, Apple has applied this feature (along with a few others) to make the Dispatch framework much more Swifty. (And Core Graphics, too.) If you've been following the Swift open-source efforts, this isn't news, but now is the first time it's part of Xcode.
Your first step on moving any project to Swift 3 should be to open it in Xcode 8 and choose Edit > Convert > To Current Swift Syntax... in the menu. This will apply (with your review and approval) all of the changes at once needed for all the renamed APIs and other changes. (Often, a line of code is affected by more than one of these changes at once, so responding to error fix-its individually might not handle everything right.)
The result is that the common pattern for bouncing work to the background and back now looks like this:
// Move to a background thread to do some long running work
DispatchQueue.global(qos: .userInitiated).async {
let image = self.loadOrGenerateAnImage()
// Bounce back to the main thread to update the UI
DispatchQueue.main.async {
self.imageView.image = image
}
}
Note we're using .userInitiated instead of one of the old DISPATCH_QUEUE_PRIORITY constants. Quality of Service (QoS) specifiers were introduced in OS X 10.10 / iOS 8.0, providing a clearer way for the system to prioritize work and deprecating the old priority specifiers. See Apple's docs on background work and energy efficiency for details.
By the way, if you're keeping your own queues to organize work, the way to get one now looks like this (notice that DispatchQueueAttributes is an OptionSet, so you use collection-style literals to combine options):
class Foo {
let queue = DispatchQueue(label: "com.example.my-serial-queue",
attributes: [.serial, .qosUtility])
func doStuff() {
queue.async {
print("Hello World")
}
}
}
Using dispatch_after to do work later? That's a method on queues, too, and it takes a DispatchTime, which has operators for various numeric types so you can just add whole or fractional seconds:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
print("Are we there yet?")
}
You can find your way around the new Dispatch API by opening its interface in Xcode 8 -- use Open Quickly to find the Dispatch module, or put a symbol (like DispatchQueue) in your Swift project/playground and command-click it, then brouse around the module from there. (You can find the Swift Dispatch API in Apple's spiffy new API Reference website and in-Xcode doc viewer, but it looks like the doc content from the C version hasn't moved into it just yet.)
See the Migration Guide for more tips.
| 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.
self.dismiss(animated: true, completion: nil)
animation value you can set according to your requirement.
| 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) then it returns minutes, if(minutes > 60) return hours and if(hours > 24) return days and so on.
How should I go about this?
EDIT: The current accepted answer has done exactly what I've wanted to do. I recommend it for easy usage for getting the time between two dates in the form that that PHP time() function uses. If you aren't particularly familiar with PHP, that's the time in seconds from January 1st, 1970. This is beneficial for a backend in PHP. If perhaps you're using a backend like NodeJS you might want to consider some of the other options you'll find below.
| 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 ?? 0
}
/// Returns the amount of months from another date
func months(from date: Date) -> Int {
return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
}
/// Returns the amount of weeks from another date
func weeks(from date: Date) -> Int {
return Calendar.current.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
}
/// Returns the amount of days from another date
func days(from date: Date) -> Int {
return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
}
/// Returns the amount of hours from another date
func hours(from date: Date) -> Int {
return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
}
/// Returns the amount of minutes from another date
func minutes(from date: Date) -> Int {
return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
}
/// Returns the amount of seconds from another date
func seconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
/// Returns the a custom time interval description from another date
func offset(from date: Date) -> String {
if years(from: date) > 0 { return "\(years(from: date))y" }
if months(from: date) > 0 { return "\(months(from: date))M" }
if weeks(from: date) > 0 { return "\(weeks(from: date))w" }
if days(from: date) > 0 { return "\(days(from: date))d" }
if hours(from: date) > 0 { return "\(hours(from: date))h" }
if minutes(from: date) > 0 { return "\(minutes(from: date))m" }
if seconds(from: date) > 0 { return "\(seconds(from: date))s" }
return ""
}
}
Using Date Components Formatter
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.second, .minute, .hour, .day, .weekOfMonth, .month, .year]
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = .full
dateComponentsFormatter.string(from: Date(), to: Date(timeIntervalSinceNow: 4000000)) // "1 month"
let date1 = DateComponents(calendar: .current, year: 2014, month: 11, day: 28, hour: 5, minute: 9).date!
let date2 = DateComponents(calendar: .current, year: 2015, month: 8, day: 28, hour: 5, minute: 9).date!
let years = date2.years(from: date1) // 0
let months = date2.months(from: date1) // 9
let weeks = date2.weeks(from: date1) // 39
let days = date2.days(from: date1) // 273
let hours = date2.hours(from: date1) // 6,553
let minutes = date2.minutes(from: date1) // 393,180
let seconds = date2.seconds(from: date1) // 23,590,800
let timeOffset = date2.offset(from: date1) // "9M"
let date3 = DateComponents(calendar: .current, year: 2014, month: 11, day: 28, hour: 5, minute: 9).date!
let date4 = DateComponents(calendar: .current, year: 2015, month: 11, day: 28, hour: 5, minute: 9).date!
let timeOffset2 = date4.offset(from: date3) // "1y"
let date5 = DateComponents(calendar: .current, year: 2017, month: 4, day: 28).date!
let now = Date()
let timeOffset3 = now.offset(from: date5) // "1w"
| 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 programming so if someone could help me creating this layout, that would be highly appreciated.
This is what I mean by "bottom sheet":
| 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's MapKit.
Example
1- Create 2 view controllers e.g, MapViewController and BottomSheetViewController. The first controller will host the map and the second is the bottom sheet itself.
Configure MapViewController
Create a method to add the bottom sheet view.
func addBottomSheetView() {
// 1- Init bottomSheetVC
let bottomSheetVC = BottomSheetViewController()
// 2- Add bottomSheetVC as a child view
self.addChildViewController(bottomSheetVC)
self.view.addSubview(bottomSheetVC.view)
bottomSheetVC.didMoveToParentViewController(self)
// 3- Adjust bottomSheet frame and initial position.
let height = view.frame.height
let width = view.frame.width
bottomSheetVC.view.frame = CGRectMake(0, self.view.frame.maxY, width, height)
}
And call it in viewDidAppear method:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
addBottomSheetView()
}
Configure BottomSheetViewController
1) Prepare background
Create a method to add blur and vibrancy effects
func prepareBackgroundView(){
let blurEffect = UIBlurEffect.init(style: .Dark)
let visualEffect = UIVisualEffectView.init(effect: blurEffect)
let bluredView = UIVisualEffectView.init(effect: blurEffect)
bluredView.contentView.addSubview(visualEffect)
visualEffect.frame = UIScreen.mainScreen().bounds
bluredView.frame = UIScreen.mainScreen().bounds
view.insertSubview(bluredView, atIndex: 0)
}
call this method in your viewWillAppear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
prepareBackgroundView()
}
Make sure that your controller's view background color is clearColor.
2) Animate bottomSheet appearance
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animateWithDuration(0.3) { [weak self] in
let frame = self?.view.frame
let yComponent = UIScreen.mainScreen().bounds.height - 200
self?.view.frame = CGRectMake(0, yComponent, frame!.width, frame!.height)
}
}
3) Modify your xib as you want.
4) Add Pan Gesture Recognizer to your view.
In your viewDidLoad method add UIPanGestureRecognizer.
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
view.addGestureRecognizer(gesture)
}
And implement your gesture behaviour:
func panGesture(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
let y = self.view.frame.minY
self.view.frame = CGRectMake(0, y + translation.y, view.frame.width, view.frame.height)
recognizer.setTranslation(CGPointZero, inView: self.view)
}
Scrollable Bottom Sheet:
If your custom view is a scroll view or any other view that inherits from, so you have two options:
First:
Design the view with a header view and add the panGesture to the header. (bad user experience).
Second:
1 - Add the panGesture to the bottom sheet view.
2 - Implement the UIGestureRecognizerDelegate and set the panGesture delegate to the controller.
3- Implement shouldRecognizeSimultaneouslyWith delegate function and disable the scrollView isScrollEnabled property in two case:
The view is partially visible.
The view is totally visible, the scrollView contentOffset property is 0 and the user is dragging the view downwards.
Otherwise enable scrolling.
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
let gesture = (gestureRecognizer as! UIPanGestureRecognizer)
let direction = gesture.velocity(in: view).y
let y = view.frame.minY
if (y == fullView && tableView.contentOffset.y == 0 && direction > 0) || (y == partialView) {
tableView.isScrollEnabled = false
} else {
tableView.isScrollEnabled = true
}
return false
}
NOTE
In case you set .allowUserInteraction as an animation option, like in the sample project, so you need to enable scrolling on the animation completion closure if the user is scrolling up.
Sample Project
I created a sample project with more options on this repo which may give you better insights about how to customise the flow.
In the demo, addBottomSheetView() function controls which view should be used as a bottom sheet.
Sample Project Screenshots
- Partial View
- FullView
- Scrollable View
| 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 define enums for every type of error I throw. Ideally, I'd like to be able mimic the example above as closely as possible. I looked into creating a custom class that implements the ErrorType protocol, but I can't even figure out that what that protocol requires. Ideas?
| 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 MyError.runtimeError(let errorMessage) {
print(errorMessage)
}
If you wish to use existing Error types, the most general one would be an NSError, and you could make a factory method to create and throw one with a custom message.
| 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: url, fileTypeHint: nil)
} catch _{
return
}
bgMusic.numberOfLoops = 1
bgMusic.prepareToPlay()
if (Data.backgroundMenuPlayed == 0){
player.play()
Data.backgroundMenuPlayed = 1
}
}
| 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 = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
Swift 3
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Swift 4 (iOS 13 compatible)
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Make sure to change the name of your tune as well as the extension.
The file needs to be properly imported (Project Build Phases > Copy Bundle Resources). You might want to place it in assets.xcassets for
greater convenience.
For short sound files you might want to go for non-compressed audio formats such as .wav since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3 etc. pp. Check the compatible audio formats of CoreAudio.
Fun-fact: There are neat little libraries which make playing sounds even easier. :)
For example: SwiftySound
| 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 = text.dataUsingEncoding(NSUTF8StringEncoding)!
var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
return json
}
I make this function in Objective-C :
- (NSDictionary*)convertStringToDictionary:(NSString*)string {
NSError* error;
//giving error as it takes dic, array,etc only. not custom object.
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
return json;
}
| 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]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let dict = convertToDictionary(text: str)
Swift 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str)
Original Swift 1 answer:
func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str) // ["name": "James"]
if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}
In your version, you didn't pass the proper parameters to NSJSONSerialization and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
and of course you would also need to change the return type of the function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
| 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<String>
print(myArray) // [b, a]
| 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 you can do in playgrounds can now be used directly in source code documentation.
For full details of the syntax, see Markup Formatting Reference. Note that there are some discrepancies between the syntax for rich playground comments & symbol documentation; these are pointed out in the document (e.g. block quotes can only be used in playgrounds).
Below is an example and a list of the syntax elements that currently work for symbol documentation comments.
Updates
Xcode 7 beta 4 ~ Added "- Throws: ..." as a top-level list item which appears alongside parameters and return descriptions in Quick Help.
Xcode 7 beta 1 ~ Some significant changes to syntax with Swift 2 - documentation comments now based on Markdown (same as playgrounds).
Xcode 6.3 (6D570) ~ Indented text is now formatted as code blocks, with subsequent indentations being nested. It doesn't appear to be possible to leave a blank line in such a code block - trying to do so results in the text being tacked onto the end of the last line with any characters in it.
Xcode 6.3 beta ~ Inline code can now be added to documentation comments using backticks.
Example for Swift 2
/// Text like this appears in "Description".
///
/// Leave a blank line to separate further text into paragraphs.
///
/// You can use bulleted lists (use `-`, `+` or `*`):
///
/// - Text can be _emphasised_
/// - Or **strong**
///
/// Or numbered lists:
///
/// 7. The numbers you use make no difference
/// 0. The list will still be ordered, starting from 1
/// 5. But be sensible and just use 1, 2, 3 etc…
///
/// ---
///
/// More Stuff
/// ==========
///
/// Code
/// ----
///
/// Use backticks for inline `code()`. Indentations of 4 spaces or more will create a code block, handy for example usage:
///
/// // Create an integer, and do nothing with it
/// let myInt = 42
/// doNothing(myInt)
///
/// // Also notice that code blocks scroll horizontally instead of wrapping.
///
/// Links & Images
/// --------------
///
/// Include [links](https://en.wikipedia.org/wiki/Hyperlink), and even images:
///
/// 
///
/// - note: That "Note:" is written in bold.
/// - requires: A basic understanding of Markdown.
/// - seealso: `Error`, for a description of the errors that can be thrown.
///
/// - parameters:
/// - int: A pointless `Int` parameter.
/// - bool: This `Bool` isn't used, but its default value is `false` anyway…
/// - throws: A `BadLuck` error, if you're unlucky.
/// - returns: Nothing useful.
func doNothing(int: Int, bool: Bool = false) throws -> String {
if unlucky { throw Error.BadLuck }
return "Totally contrived."
}
Syntax for Swift 2 (based on Markdown)
Comment Style
Both /// (inline) and /** */ (block) style comments are supported for producing documentation comments. While I personally prefer the visual style of /** */ comments, Xcode's automatic indentation can ruin formatting for this comment style when copying/pasting as it removes leading whitespace. For example:
/**
See sample usage:
let x = method(blah)
*/
When pasting, the code block indentation is removed and it is no longer rendered as code:
/**
See sample usage:
let x = method(blah)
*/
For this reason, I generally use ///, and will use it for the rest of the examples in this answer.
Block Elements
Heading:
/// # My Heading
or
/// My Heading
/// ==========
Subheading:
/// ## My Subheading
or
/// My Subheading
/// -------------
Horizontal rule:
/// ---
Unordered (bulleted) lists:
/// - An item
/// - Another item
You can also use + or * for unordered lists, it just has to be consistent.
Ordered (numbered) lists:
/// 1. Item 1
/// 2. Item 2
/// 3. Item 3
Code blocks:
/// for item in array {
/// print(item)
/// }
An indentation of at least four spaces is required.
Inline Elements
Emphasis (italics):
/// Add like *this*, or like _this_.
Strong (bold):
/// You can **really** make text __strong__.
Note that you cannot mix asterisks (*) and underscores (_) on the same element.
Inline code:
/// Call `exampleMethod(_:)` to demonstrate inline code.
Links:
/// [Link Text](https://en.wikipedia.org/wiki/Hyperlink)
Images:
/// 
The URL can be either a web URL (using "http://") or an absolute file path URL (I can't seem to get relative file paths to work).
The URLs for links and images can also be separated from the inline element in order to keep all URLs in one, manageable place:
/// A [link][1] an an ![image][2]
///
/// ...
///
/// [1]: http://www.example.com
/// [2]: http://www.example.com/image.jpg
Keywords
In addition to the Markdown formatting, Xcode recognises other markup keywords to display prominently in Quick Help. These markup keywords mostly take the format - <keyword>: (the exception is parameter, which also includes the parameter name before the colon), where the keyword itself can be written with any combination of uppercase/lowercase characters.
Symbol Section keywords
The following keywords are displayed as prominent sections in the help viewer, below the "Description" section, and above the "Declared In" section. When included, their order is fixed as displayed below even though you can include them in whatever order you like in your comments.
See the fully documented list of section keywords and their intended uses in the Symbol Section Commands section of the Markup Formatting Reference.
/// - parameters:
/// - <#parameter name#>:
/// - <#parameter name#>:
/// - throws:
/// - returns:
Alternatively, you can write each parameter this way:
/// - parameter <#parameter name#>:
Symbol Description Field keywords
The following list of keywords are displayed as bold headings in the body of the "Description" section of the help viewer. They will appear in whatever order you write them in, as with the rest of the "Description" section.
Full list paraphrased from this excellent blog article by Erica Sadun. Also see the fully documented list of keywords and their intended uses in the Symbol Description Field Commands section of the Markup Formatting Reference.
Attributions:
/// - author:
/// - authors:
/// - copyright:
/// - date:
Availability:
/// - since:
/// - version:
Admonitions:
/// - attention:
/// - important:
/// - note:
/// - remark:
/// - warning:
Development State:
/// - bug:
/// - todo:
/// - experiment:
Implementation Qualities:
/// - complexity:
Functional Semantics:
/// - precondition:
/// - postcondition:
/// - requires:
/// - invariant:
Cross Reference:
/// - seealso:
Exporting Documentation
HTML documentation (designed to mimic Apple's own documentation) can be generated from inline documentation using Jazzy, an open-source command-line utility.
$ [sudo] gem install jazzy
$ jazzy
Running xcodebuild
Parsing ...
building site
jam out ♪♫ to your fresh new docs in `docs`
Console example taken from this NSHipster article
| Swift | 24,047,991 | 255 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.