I'm new in iOS and Swift development, and i'm not used to manage the network reachability in my usual programs.
I found AFNetworking and Alamofire which are great frameworks to ease the API calls in iOS.
But i have difficulties to figure out how to make some requests to wait until network is back if i'm loosing it.
Typically during session login or getting some json lists or downloading images.
Do you have some tutorials or examples i can rely on to improve my knowledge and be able to build a strong application resilient to network availability ?
now Alamofire has just included a Network status listener
https://github.com/Alamofire/Alamofire/pull/1053
Alamofire now has a network reachability manager
This is from their github page -
let manager = NetworkReachabilityManager(host: "your.server.url.com")
manager?.listener = { status in
print("Network Status Changed: \(status)") }
manager?.startListening()
Related
My application has been rejected twice for Incompatibility over Ipv6 network.
This question has been asked several times. Most of the solutions suggested to avoid using third party api for http request and do not hard code ipaddress. I have not done neither.
However does my server have to be ipv6 compatible or is there something wrong with my http request.
So I tested my server https://services.fingrowthbank.com/ on this website http://ipv6-test.com/validate.php for Ipv6 readiness testing. It shows as incompatible. Could this be a reason for the rejection?
Code for http request
let nsUrlObject: NSURL = NSURL(string: urlAndMethod)!
let nsMutableUrlRequestObj: NSMutableURLRequest = NSMutableURLRequest(URL: nsUrlObject, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: nstime_out_intervalObj)
nsMutableUrlRequestObj.HTTPMethod = “POST"
let bodyData = httpBodyStr
nsMutableUrlRequestObj.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
nsMutableUrlRequestObj.setValue(httpHeaderStr, forHTTPHeaderField: "Authorization")
NSURLConnection.sendAsynchronousRequest(nsMutableUrlRequestObj, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
if response == nil
{
print(error)
alert.view.removeFromSuperview()
Imps_http_client.showAlertView("Could not connect to the server")
}else{
}
}
There is no problem with your code. The problem is your server side.
As per https://services.fingrowthbank.com/ your server is not compatibility with IPV6. Because I found that you are using old security encryption i.e, Obsolete Cipher suite .
I under lined inside the image.
I tested with sample server. Example: Apple. This apple is using modern cipher suite
The problem with your server there is a chance of security attack number 13. This is the reason the apple is rejected your app. Update your app with late security.
Solution: Just update your server to modern cipher suite.
This url is perfectly fine as far as your are using domain name for sending request to server.
according to apple If you’re writing a client-side app using high-level networking APIs such as NSURLSession and the CFNetwork frameworks and you connect by name, you should not need to change anything for your app to work with IPv6 addresses. If you aren’t connecting by name, you probably should be.
check your code or any third party components you are using and make sure your are not sending any request with IP address instead of domain name. Specifically, Check Reacahbility code. If you are using it, don't use function reachabilityWithAddress , use reachabilityWithHostName instead. reachabilityForInternetConnection is also using reachabilityWithAddress - If you are using this, then edit it.
At last, you can validate your app for ipv6 by creating ipv6 network with mac and testing app with that network.
We are trying out Kurento 6.0 + Java Spring Client. The Examples works well (one2one call + one2one-recording). We are trying to implement the same functionality on an IOS app so that we can do Peer (IOS) -> Peer (Web) calls. But unfortunately - the documentation is not very clear.
The Kurento Server and Java Spring Boot application are deployed to an AWS ec2 instance and stun servers are configured.
We are using the call https://kurento-IP:8443/call with json to register:
var message = {
id : 'register',
name : name
};
ws.send(message)
And it works!
Question:
How can we now initiate a call in IOS after that?
Should the iOS be communicating to the Spring App (https://kurento-IP:8443/call) or directly to ws://kurento-ip:8888/kurento (We guess should be both?)
On the Web the JS does the following to make a call:
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function(error) {
if (error) {
return console.error(error);
}
this.generateOffer(onOfferCall);
});
onOfferCall - calls directly the Web!
We were looking into the Kurento IOS documentation, but couldn't yet figure out. How can we convert this into IOS?
Any help would be highly appreciated!
Your iOS app should be sending the messages to the signaling server. I'd suggest you read this small introduction from the documentation, and spend some time understanding where your application architecture fits in this diagram
Hint: It's not the first one ;-)
I need something similar to Facebook's offline post capabilities. Basically I want users to create content locally on the device regardless of connection state, and whenever internet becomes available it should POST/PUT to the server.
I've searched the internet for a solution and I found that NSURLSessionUploadTask can be used for POST-ing in the background. But I couldn't figure out if the following scenarios are supported:
Will my task remain in the background queue when the user is offline and will the operating system try to execute items in the queue upon reconnecting with a network?
What happens if the application is force-closed by the user or crashes?
What happens if the operation fails?
First of all, background NSURLSession allows file upload only. If that is ok for you:
The task will be in the queue until it receives a server answer.
If your app is force-closed, the task will still be executing. When the request is done, your app will be launched in non-interactive background state and receive application:handleEventsForBackgroundURLSession:completionHandler:. After you process the signal and call the completion handler or 30 second timeout, the app will be closed.
I the operation fails, you will receive URLSession:task:didCompleteWithError:
There is a good tutorial on background NSURLSessions. I suggest you to read all 4 parts of this great article.
If file upload is not an option for you, i suggest you to save information into local database and then wait for internet is reachable. (a good approach here is use of Reachability library, Alamofire allows to do that too). When internet becomes available, simply call your http requests with saved data.
We were running into connectivity issues with our internal apps, so we wrote a Swift framework that allows any network operations to be enqueued and sent whenever the device has access to the internet -
https://cocoapods.org/pods/OfflineRequestManager. You'll still have to handle the network request itself within the object conforming to OfflineRequest, but it sounds like a good fit for your use case.
The simplest use case would look something like the following, though most actual cases (saving to disk, specific request data, etc.) will have a few more hoops to jump through:
import OfflineRequestManager
class SimpleRequest: OfflineRequest {
func perform(completion: #escaping (Error?) -> Void) {
doMyNetworkRequest(withCompletion: { response, error in
handleResponse(response)
completion(error)
})
}
}
///////
OfflineRequestManager.defaultManager(queueRequest: SimpleRequest())
I'm a bit lost on AFNetorking's Reachability and haven't found a lot of good information out there.
I have an app that logs into a web API. Each VC connects to the API in some way so each VC needs to have network access. I use a subclass of AFHTTPSessionManager to make network requests.
I am confused as to where to put the code - is it just the appDelegate or is it in each VC?
What is the use of this code?
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
}];
And where do you use these methods and how do they relate to the code above?
-startMonitoring
-stopMonitoring
The -startMonitoring method of AFNetworking is used to make your AFNetworkReachabilityManager start monitoring the network connection. If you do not call -startMonitoring, your setReachabilityStatusChangeBlock will never be called (regardless of where you put it) since AFNetworking isn't monitoring your connection.
As you probably assumed, -stopMonitoring does the exact opposite of -startMonitoring - it stops the manager from checking network connectivity. I normally don't use this method in my apps, but if your app doesn't need a network connection for a certain part of it, feel free to call it (just make sure you start monitoring the network again when you need to).
The setReachabilityStatusChangeBlock is called whenever the network status changes. You can put this wherever you want to make changes if/when the network changes. An example of this would be putting it in your app delegate and sending out a NSNotification when the network status changes so that any view controller observing the notification can react appropriately.
You can also manually check to see if the network is online (as long as -startMonitoring was called and AFNetworking is monitoring your network) using something like this:
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
NSLog(#"Online");
}
You can read more on AFNetworking's official documentation on GitHub.
I am developing an iPhone app which is using CocoaHTTPServer for making remote server communication.
The app will send the request details to the CocoaHTTPServer which will store the request locally. Once the internet connectivity is available, CocoaHTTPServer will send the request to remote server & will get the server response now CocoaHTTPServer has to send this response back to the app,
But I am confused how to implement it. Is there any inter app communication api for the same?
Any suggestions are greatly appreciated.
Well , I haven't workaround CocoaHTTP server classes so can't explain you verywell but I found there are couple of tutorials will surly guide you.
Thanks to Matt Gallagher for such a detailed article.
You can listen for a connection using NSFileHandle class
listeningHandle = [[NSFileHandle alloc]
initWithFileDescriptor:fileDescriptor
closeOnDealloc:YES];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(receiveIncomingConnectionNotification:)
name:NSFileHandleConnectionAcceptedNotification
object:nil];
[listeningHandle acceptConnectionInBackgroundAndNotify];
When receiveIncomingConnectionNotification: is invoked, each new incoming connection will get its own NSFileHandle. If you're keeping track, you can handle received message
if(CFHTTPMessageIsHeaderComplete(incomingRequest))
{
HTTPResponseHandler *handler =
[HTTPResponseHandler
handlerForRequest:incomingRequest
fileHandle:incomingFileHandle
server:self];
[responseHandlers addObject:handler];
[self stopReceivingForFileHandle:incomingFileHandle close:NO];
[handler startResponse];
return;
}
Note : please go through the full article, it has nice explanation.
Apart from this you may have look on this as well.
Hope this will give you some idea.
You question is focussing on background proces.
When an App goes into background, it get very limited time to finish things up. After that the App freezes in background. That is not a good situation to start communication.
Apple states clearly that the priority is always on the running foreground tasks.
The Notification mechanism (as listed by RDC above) is created to handle external events. During such a wake up you can send/receive a little bit of data, however you'll get minimal priority. Since timing is important in communication, I would not go for that either.
I suggest checking communication during the wakeup call and start activities then. And use the Notification mechanism to wakeup the user, that network is up again.
URL scheme can be used to send the response back to the app. The response from the remote server can be set as a parameter in the URL. The CocoaHTTPServer can invoke the other app which will be the handler of this unique URL. The below link provides more information on the same.
Inter-AppCommunication using URL scheme