CFNetwork

RSS for tag

Access network services and handle changes in network configurations using CFNetwork.

CFNetwork Documentation

Pinned Posts

Posts under CFNetwork tag

153 Posts
Sort by:
Post marked as solved
1 Replies
274 Views
Hi, I have an app on the AppStore, but a few times, I get reports from users that he gets -1003 "Could not find a server with the specified hostname" on a 4G network. I tested on my iphone app and the problem is normal. Knowing that -1003 doesn't happen to all users, maybe there is some setting on the phone that is causing this? Or is there a way to help the user to fix it (reboot or Wifi)? If anyone knows the problem please let me know, thanks.
Posted
by
Post not yet marked as solved
8 Replies
563 Views
I am trying to set up an HTTP proxy that can be used system-wide from an app. After some research, it looks like the CoreFoundation library's CFNetworkExecuteProxyAutoConfigurationScript() function can be used to configure the proxy. (1) Is it possible to set the HTTP proxy available system-wide with CFNetworkExecuteProxyAutoConfigurationScript()? (2) I tried the following source code but "EXC_BAD_ACCESS" occurs and the callback block is not called. Do you know what is the problem? (void)startNextRequest { Request *request = _requests.firstObject; if (request == nil) { return; } CFStreamClientContext context; memset(&context, 0, sizeof(CFStreamClientContext)); context.info = (__bridge void * _Null_unspecified)(self); CFRunLoopSourceRef rls = CFNetworkExecuteProxyAutoConfigurationScript( (__bridge CFStringRef _Nonnull)(_script), (__bridge CFURLRef _Nonnull)(request.targetURL), (__bridge void *)^(PACResolver *client, CFArrayRef proxies, CFErrorRef error) { [client resolveDidFinishWithProxies:proxies error:error]; }, &context); assert(_runLoopSource == nil); _runLoopSource = rls; CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode); } Environment: Xcode 13.1 iPad 8th gen. iOS 14.0.1
Posted
by
Post not yet marked as solved
3 Replies
426 Views
We have been seeing a NSURLError cannot parse error with error code -1017 for 0.01% of all the requests fired from our native app. We double checked the request headers and cookies but found no difference from the API calls that succeeded for the same path. For most of these requests, we found (through our analytics tools) that 99% of the times, there was no response received from the server(response object is nil); trying to understand why would a no response cause a cannot parse error. We do not get much information from error received as to what really went wrong, did the request even reach the server or was killed or modified by the OS? Any help or further detail will be very helpful. Error in detail: Foundation.URLError(_nsError: Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" UserInfo={NSUnderlyingError=0x280eddc50 {Error Domain=kCFErrorDomainCFNetwork Code=-1017 "(null)" UserInfo={_kCFStreamErrorCodeKey=-1, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://mydomain.com/path, NSErrorFailingURLKey=https://mydomain.com/path, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1, NSLocalizedDescription=cannot parse response})
Posted
by
Post not yet marked as solved
1 Replies
312 Views
Hi all I am experiencing some odd behavior when I use CFNetworkCopyProxiesForURL. Namely, it works perfectly for unauthenticated http/https and auto configure (proxy.pac) files, but it seems to assume that credentialed proxies are not valid for the the given URL, returning a result of kCFProxyTypeNone whenever I attempt to use a credentialed proxy. If it instead use SCDynamicStoreCopyProxies to get the system proxies and use the first one found, it works correctly to proxy my connection to the destination, but I would rather use CFNetworkCopyProxiesForURL if possible as that would be more specific. (lldb) n Process 2789 stopped * thread #61, queue = 'com.apple.root.default-qos', stop reason = step over   frame #0: 0x00000002f858e868 myprocess.dylib`get_proxy_settings_for_url(uri=0x0000600000c40010) at my_proxy.mm:315:33    312   // We have to use a unique ptr type here because of the COPY in the function name, which tells us we take ownership    313   auto proxies = apple::cf_ptr<CFArrayRef>{ CFNetworkCopyProxiesForURL(target_uri_ref.get(),    314                                      system_proxies.get()) }; -> 315   if (CFArrayGetCount(proxies.get()) == 0 )    316   {    317     LOG_INFO("No proxy configuration found"_ts);    318     return std::nullopt; Target 0: (myprocess) stopped. (lldb) po proxies.get() <__NSArrayM 0x600000c16130>( {   kCFProxyTypeKey = kCFProxyTypeNone; } ) (lldb) po system_proxies.get() {   ExceptionsList =   (     "192.168.1.61"   );   HTTPEnable = 1;   HTTPPort = 3128;   HTTPProxy = "192.168.1.61";   HTTPUser = mike;   "__SCOPED__" =   {     en0 =     {       ExceptionsList =       (         "192.168.1.61"       );       HTTPEnable = 1;       HTTPPort = 3128;       HTTPProxy = "192.168.1.61";       HTTPUser = mike;     };   }; } (lldb) po target_uri_ref.get() https://mycompany.com/mac Thanks! Alex
Posted
by
Post not yet marked as solved
1 Replies
354 Views
Hi there, I'm currently initializing a cookie that is supposed to be http only for the security purposes. However, I can't find a way to set the cookie to be http only. Could anyone point me to the right direciton? let cookie = HTTPCookie(properties: [         .domain: "aaa.bbbb.ccc",         .path: "/",         .name: "token",         .value: "aaa.bbb.ccc",         .version: 1,         .secure: true,         .expires: NSDate(timeIntervalSinceNow: 12345)     ])!
Posted
by
Post not yet marked as solved
6 Replies
385 Views
Hello! The documentation on ATS refers to "apps and app extensions" as scope. https://developer.apple.com/documentation/security/preventing_insecure_network_connections Does this limit its availability to apps that are running in the user context? The question is: do we get ATS protection in case of a launchd job? Let's say there is a launchd job (running in uid 1 context). It initiates network requests using URLSession API. Does it get ATS by default? Is there a way to validate that? Is it correct to assume that high level network API such as URLSession use ATS by default? Thanks. Best regards, Arthur
Posted
by
Post not yet marked as solved
1 Replies
251 Views
I was going through the documentation of dataTaskWithRequest:completionHandler: method of NSURLSession https://developer.apple.com/documentation/foundation/nsurlsession/1407613-datataskwithrequest The completion handler has the third param as NSError. But I could not find the domain name for these errors. Is it expected to be NSURLErrorDomain if the error is related to the network request? Or is it kCFErrorDomainCFNetwork. Is there any exhaustive list of error domain names that one can encounter for the above method? Thanks!
Posted
by
VC2
Post marked as solved
2 Replies
247 Views
I am updating an old app, and my old code which uploads POST messages to a PHP script is not working. It seems like the POST array is simply empty. I've looked online and my code looks just like all the examples I see. just tried the answer given here, a simple example, and I get nothing in the POST array: https://stackoverflow.com/questions/28654603/php-post-script-works-with-other-sites-but-not-with-ios-nsurlconnection Here is the code from that example that does not work for me: @implementation Test : NSObject -(void)userLogin { NSString *user = @"test"; NSString *pass = @"pass"; NSString *post = [NSString stringWithFormat: @"user=%@&amp;pass=%@", user, pass]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%lu", [postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; [request setURL:[NSURL URLWithString:@"www.example.com/login.php"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; sleep(50); NSLog(@"%@", conn); } @end --------------- PHP file ----------------------- &lt;?php file_put_contents('/tmp/test', print_r($_POST, true)); ?&gt; On the other hand, if I go to a site like this and send a message with a simple 'user=me' and 'pass=whatever', then my php script does show that it received the variables. https://reqbin.com/post-online Furthermore, if I go to a site that will receive POSTs, like this one, then the example code above works fine. http://ptsv2.com Anyone know what could be the issue?
Posted
by
Post marked as solved
5 Replies
593 Views
Hi, I'm working in a iOS app using the UIImagePickerController to get files and videos from the photo library and upload to Azure Blob storage. For images, everything is working fine, but for videos, it fails with the following error: Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted" UserInfo={_kCFStreamErrorCodeKey=1, _kCFStreamErrorDomainKey=1} Basically, what I'm doing is: 1.to get the file URL from the UIImagePickerController:                 if mediaType == "public.movie" {                     let mediaURL = info[UIImagePickerController.InfoKey.mediaURL] as! NSURL                                          uploadFileAsync(fileURL: mediaURL.filePathURL)                 } the upload to Azure method:  func uploadFileAsync(fileURL: URL) { ... do { let isSecureAccess = fileURL.startAccessingSecurityScopedResource() defer{fileURL.stopAccessingSecurityScopedResource()} let resourceValues = try fileURL.resourceValues(forKeys: [.fileSizeKey]) // Gets the Mime Type let extUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension as CFString, nil)?.takeUnretainedValue() let mimeType:String = extUTI != nil ? (UTTypeCopyPreferredTagWithClass(extUTI!, kUTTagClassMIMEType)?.takeUnretainedValue() as String?) ?? defaultMimeType : defaultMimeType let fileSize: Int = resourceValues.fileSize! blockBlob?.properties.length = NSNumber(value: fileSize) blockBlob?.properties.contentType = mimeType blockBlob?.uploadFromFile(with: fileURL) } The error is generating from the blockBlob?.uploadFromFile(with: fileURL) Any help is really appreciated.
Posted
by
Post marked as solved
2 Replies
289 Views
Set up Charles well, and can monitor the network requests on the app, when the app is in foreground. The app receive a background notification, will trigger to make a api call. But the api call cannot be shown in Charles when the app in backgroud. Do ios do some disguise for background network request, so that cannot be shown in Charles? Or it should can be monitored, additional settings required? thx for anyone could share related experience
Posted
by
Post not yet marked as solved
4 Replies
454 Views
I maintain a large production app which uses background-configured URLSession to upload large numbers of files concurrently to our servers using PUT requests. These are file based uploads (https://developer.apple.com/documentation/foundation/urlsession/1411550-uploadtask) as required by background URLSessions to be support. We concurrently upload up to 16 files at once, although the configuration specifies only configuration.httpMaximumConnectionsPerHost = 4 When our servers migrated to Http2, I noticed that users who were uploading concurrently were returned many errors by URLSession. Specially through the delegate method  urlSession(session: task: didCompleteWithError:), the error returned was NSURLErrorCannotParseResponse which has little documentation or public discussion. When our servers reverted this Http2 change, back to regular Http1.1, this stopped happening. No change in the actual server response was made. Since iOS negotiates the protocol the connection uses without our applications involvement, I cannot seem to choose a network protocol to force http1.1. I also, cannot see any other details from this NSError (no underlying error or other obvious issues). All I can do is log the network protocol via task metrics. It seems that when this error occurs, its as if the urlsessiond has crashed or the network stack just falls apart and I get many NSURLErrorCannotParseResponse all at once before users can manually retry these failures. This URLSession is configured by let configuration = URLSessionConfiguration.background(withIdentifier: backgroundIdentifier) configuration.waitsForConnectivity = true configuration.allowsExpensiveNetworkAccess = true configuration.httpMaximumConnectionsPerHost = 4 This is not a good experience and I have no other way to solve these errors. Does anyone have advice for this scenario?
Posted
by
Post not yet marked as solved
2 Replies
347 Views
I wanted to implement a retry mechanism for a NSURLSessionDataTask. In android I am seeing that we can simply set a retry policy for the volley request as such myRequest.setRetryPolicy(new DefaultRetryPolicy( (int) TimeUnit.SECONDS.toMillis(200), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Ref: https://afzaln.com/volley/com/android/volley/DefaultRetryPolicy.html I tried finding something similar for NSURLSessionDataTask but havent been able to find it yet. Is there any iOS SDK support for this? Or do we need to implement something like below pseudocode for retries with backoff? self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; [self callServiceWithRetries:3 timeAtStart:[NSDate date] andTimeOut:200]; id callServiceWithRetries:(int)retries timeAtStart:(NSDate)timeAtStart andTimeOut:(int)timeout{ __weak __typeof(self) weakSelf = self; NSURLRequest *request = //create request NSDate *startDate = [NSDate date]; NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSDate *endDate = [NSDate date]; NSInterval timeIntervalSinceStart = [endDate timeIntervalSinceDate:timeAtStart]; NSInteger timeSinceStart = ((timeIntervalSinceStart % 1) * 1000); if (error) { if(retries > 0 && timeSinceStart < timeOut){ // add delay/backoff here before making the request. To calculate the delay we can // use the current number of retries made. Something like exponential back off here [weakSelf callServiceWithRetries:retries - 1 timeAtStart:timeAtStart andTimeout:timeout]; } else{ //failure callback } return; } if(non 2xx error){ if(retries > 0 && timeSinceStart < timeOut){ // add delay/backoff here before making the request. To calculate the delay we can // use the current number of retries made. Something like exponential back off here [weakSelf callServiceWithRetries:retries - 1 timeAtStart:timeAtStart andTimeout:timeout]; } else{ //failure callback } } //success callback } }
Posted
by
VC2
Post marked as solved
3 Replies
303 Views
I have some code that used to work but is failing to bind to a local UDP port saying it is already in use. lsof does not show that the port is being used. Below is my receive function that fails. bindResult is "-1" when calling bind, and the error printed out contains "Address already in use (48)". I am trying to bind to 127.0.0.1:6000. This has been working for a very long time, but I've not used it for one or two months, so not sure if a macOS upgrade or something else broke it. func receive(handleRxData: @escaping (UdpSocket, IpAddress, ArraySlice&lt;UInt8&gt;) -&gt; Void,                withError error: (_ msg: String) -&gt; Void) {          self.handleRxData = handleRxData          var cfSocketContext = CFSocketContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)     cfSocketContext.info = Unmanaged.passRetained(self).toOpaque()          cfSock = CFSocketCreate(kCFAllocatorDefault,                             PF_INET,                             SOCK_DGRAM,                             IPPROTO_UDP, CFSocketCallBackType.readCallBack.rawValue,                             { (socket: CFSocket?, callBackType: CFSocketCallBackType, address: CFData?, data: UnsafeRawPointer?, info: UnsafeMutableRawPointer?) -&gt; Void in                               let udpSocket = Unmanaged&lt;UdpSocket&gt;.fromOpaque(info!).takeUnretainedValue()                               udpSocket.receiveCallback()     },                             UnsafeMutablePointer&lt;CFSocketContext&gt;(&amp;cfSocketContext))     let sock = CFSocketGetNative(cfSock)          // Create ipv4 addr struct:     var sin = sockaddr_in()     if (local.type == .ipv4) {       sin.sin_len = __uint8_t(MemoryLayout.size(ofValue: sin))       sin.sin_family = sa_family_t(AF_INET)       sin.sin_addr.s_addr = local.ipv4.bigEndian       sin.sin_port = local.port.bigEndian     }          let bindResult = withUnsafeMutablePointer(to: &amp;sin) {       $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {         bind(sock, UnsafeMutablePointer&lt;sockaddr&gt;($0), socklen_t(MemoryLayout&lt;sockaddr_in&gt;.size))       }     }     if bindResult &lt; 0 {       error("Could not bind to socket \(sin) ( \(String(cString: strerror(errno)!)) (\(errno)).")       return     }          // Change socket to non-blocking:     let flags = fcntl(sock, F_GETFL);     let fcntlResult = fcntl(sock, F_SETFL, flags | O_NONBLOCK);     if (fcntlResult &lt; 0) {       print("Could not change socket to non-blocking ( \(String(cString: strerror(errno)!)) (\(errno)).")     }     // Add to run loop:     let rls = CFSocketCreateRunLoopSource(nil, cfSock, 0);     if (rls == nil) {       error("Could not get run loop source.")       return     }     CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, CFRunLoopMode.commonModes)// CFRunLoopMode.defaultMode);   }
Posted
by
Post marked as solved
3 Replies
1.4k Views
As I am preparing for the latest iOS 15.4 rollout, I downloaded the latest Xcode 13.3 beta 2 update. To my surprise a previous standard REST call made in my app is now failing with the following network issue when running on an iPhone 13 Pro with iOS 15.4 (beta2). 2022-02-10 11:11:00.944 [Info] [main] [AlamofireNetworkService.swift:24] fetch(route:) &gt; post: https://site.serverdev.net:18100/Users?action=login 2022-02-10 11:11:01.087121-0500 MyApp[50029:13165667] [connection] nw_socket_handle_socket_event [C8.1:3] Socket SO_ERROR [54: Connection reset by peer] 2022-02-10 11:11:01.091555-0500 MyApp[50029:13165884] [boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics 2022-02-10 11:11:01.104522-0500 MyApp[50029:13165667] Connection 8: received failure notification 2022-02-10 11:11:01.104715-0500 MyApp[50029:13165667] Connection 8: received ECONNRESET with incomplete TLS handshake - generating errSSLClosedNoNotify 2022-02-10 11:11:01.105049-0500 MyApp[50029:13165667] Connection 8: failed to connect 3:-9816, reason -1 2022-02-10 11:11:01.105174-0500 MyApp[50029:13165667] Connection 8: encountered error(3:-9816) 2022-02-10 11:11:01.106574-0500 MyApp[50029:13165667] Task &lt;F53C7A17-7297-4566-9746-1D39807E8356&gt;.&lt;5&gt; HTTP load failed, 0/0 bytes (error code: -1200 [3:-9816]) 2022-02-10 11:11:01.118796-0500 MyApp[50029:13165920] Task &lt;F53C7A17-7297-4566-9746-1D39807E8356&gt;.&lt;5&gt; finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://site.serverdev.net:18100/Users%3Faction=login, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask &lt;F53C7A17-7297-4566-9746-1D39807E8356&gt;.&lt;5&gt;, _NSURLErrorRelatedURLSessionTaskErrorKey=(   "LocalDataTask &lt;F53C7A17-7297-4566-9746-1D39807E8356&gt;.&lt;5&gt;" ), NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://site.serverdev.net:18100/Users%3Faction=login, NSUnderlyingError=0x6000016e6850 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9816, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816, _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: utun3}}, _kCFStreamErrorCodeKey=-9816} I see there is an error related to the TLS handshake and following that a generic error saying "a secure connection to the server cannot be made". I ran the same call against the iPhone 13 Pro with iOS 15.0 on the same Xcode 13.3 beta2 version and the call succeeds as expected. This leaves me to believe the issue is tied to the iOS 15.4 beta layer. The release notes don't state any particular mention of SSL requirement changes and am wondering how else I can go about to investigate this issue. (The server I am communicating with enforces TLS 1.2)
Posted
by
Post not yet marked as solved
0 Replies
193 Views
Directly set the mapping relationship between domain name and IP, let my app use it with NSURLSession, Is there a related interface?
Posted
by
Post not yet marked as solved
5 Replies
588 Views
My app crashed when launch. The crash report: OS Version: iPhone OS 15.4 (19E5209h) Release Type: Beta Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: DYLD 4 Symbol missing Symbol not found: _$sSo25NSURLSessionWebSocketTaskC10FoundationE4sendyyAbCE7MessageOYaKF Referenced from: /private/var/containers/Bundle/Application/43FB5827-DE90-4FCF-A716-11A7FD5BE11E/Kingbox.app/Kingbox Expected in: /usr/lib/swift/libswiftFoundation.dylib (terminated at launch; ignore backtrace) Triggered by Thread: 0 Thread 0 Crashed: 0 dyld 0x00000001056506d0 __abort_with_payload + 8 1 dyld 0x00000001056562c8 abort_with_payload_wrapper_internal + 104 (terminate_with_reason.c:102) 2 dyld 0x00000001056562fc abort_with_payload + 16 (terminate_with_reason.c:124) 3 dyld 0x00000001056267e8 dyld4::halt(char const*) + 328 (DyldProcessConfig.cpp:2067) 4 dyld 0x0000000105623920 dyld4::prepare(dyld4::APIs&amp;, dyld3::MachOAnalyzer const*) + 3560 (dyldMain.cpp:0) 5 dyld 0x0000000105621c84 start + 488 (dyldMain.cpp:864) Demangle the symbol: _$sSo25NSURLSessionWebSocketTaskC10FoundationE4sendyyAbCE7MessageOYaKF (extension in Foundation):__C.NSURLSessionWebSocketTask.send((extension in Foundation):__C.NSURLSessionWebSocketTask.Message) async throws -&gt; ()
Posted
by
Post not yet marked as solved
4 Replies
360 Views
Is there a way for iOS NSURLSession to control dns resolution by itself, similar to the ability of the libcurl library (https://curl.se/libcurl/c/CURLOPT_RESOLVE.html). Because I found that my app's domain name was hijacked in the public network.
Posted
by