1

Trying to make TCP connection with Google mail server through IMAP protocol with "Network framework" (Swift), but I got an error. I got code from this (wwdc2018) video.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let connection = NWConnection(host: "imap.google.com", port: .imaps, using: .tls)

    let myQueue = DispatchQueue(label: "test")

    connection.stateUpdateHandler = { (newState) in
        switch (newState) {
        case .waiting(let error):
            print("ERROR - \(error)")
        case .preparing:
            print("I am HERE")
        case .ready:
            print("HELLO")
        case .failed(let error):
            print("ERROR + \(error)")
        default:
            break
        }
    }

    connection.start(queue: myQueue)

    return true
}

My console displays:

I am HERE

ERROR - -65554: NoSuchRecord

UDPATED: Thanks to @arnt I remembered that host must be "imap.gmail.com", now works fine!

The main goal is to create TCP connection with Google mail server through IMAP protocol with "Network framework", but on Objective-C.

4

1 回答 1

2

我自己试过了,我成功了!=)

const char *hostname = "imap.gmail.com";
const char *port = "imaps";
nw_parameters_t parameters = nw_parameters_create_secure_tcp(NW_PARAMETERS_DEFAULT_CONFIGURATION, NW_PARAMETERS_DEFAULT_CONFIGURATION);
nw_endpoint_t endpoint = nw_endpoint_create_host(hostname, port);
nw_connection_t connection = nw_connection_create(endpoint, parameters);

nw_connection_set_queue(connection, dispatch_get_main_queue());
nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t error) {
    switch (state) {
        case nw_connection_state_waiting:
            NSLog(@"waiting");
            break;
        case nw_connection_state_failed:
            NSLog(@"failed");
            break;
        case nw_connection_state_ready:
            NSLog(@"connection is ready");
            break;
        case nw_connection_state_cancelled:
            NSLog(@"connection is cancelled");
            break;
        default:
            break;
    }
});
nw_connection_start(connection);
于 2019-12-29T20:41:59.387 回答