I have a backend hosted on heroku using django and I have an iOS app consuming that api. Sometimes the app throws this error
locman err: Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error 0.)"
The backend for that same request throws this error
sock=client at=error code=H18 desc="Request Interrupted" status=503
How should I handle this in iOS? It seems like its a problem with the app. Am I just sending up too many requests at once?
heres what my api controller looks like
class func getPictures(location_id: String, completionHandler:( cardImageArray: [CardImage] )->() ){
var bodyString: String = "location_id=\(location_id)"
bodyString = bodyString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let url: NSURL = NSURL(string: BASE_URL + "/api/v1/get_pictures" + "?" + bodyString)!
let req: NSMutableURLRequest = NSMutableURLRequest(URL: url)
req.HTTPMethod = "GET"
//req.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
NSURLConnection.sendAsynchronousRequest(
req,
queue: NSOperationQueue.mainQueue())
{ (res: NSURLResponse!, data: NSData! , err: NSError!) -> Void in
let jsonDict = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
if (jsonDict["response"].int == 1){
var cardImageArray: [CardImage] = []
if let photo_urls = jsonDict["photo_urls"].array{
// NSString(data: data, encoding: nil)
for photo_url_raw in photo_urls{
if let url_string = photo_url_raw.string{
let ci = CardImage(urlstring: url_string)
cardImageArray.append(ci)
}
}
return completionHandler(cardImageArray: cardImageArray)
}
}else{
println("error in get pictures")
if let errorMessage = jsonDict["error"].string{
return
}
}
}
}
Figured out this was the error message being printed when location manager can't decide what the users location is. Just handled the error and had the user click a button to try again.
Related
I wonder how I can exit out of my function when request timed out.
If I put my server offline and try to do some calls with this function the app will crash due to:
fatal error: unexpectedly found nil while unwrapping an Optional value
My Alamofire v3.x function looks like this:
static func loginWithFb(facebookId: String, email: String, username: String, response: (token: String?, errorVal: JSON?) -> ()) {
let urlString = baseURL + ResourcePath.FbLogin.description
let parameters: [String: AnyObject] = [
"facebook_id": facebookId,
"user_type": 1,
"email": email,
"username": username
]
Alamofire.request(.POST, urlString, parameters: parameters).responseJSON{ (responseData) -> Void in
let json = JSON(responseData.result.value!)
let token = json["api_key"].string
response(token: token, errorVal: json)
}
}
I get nil from:
let json = JSON(responseData.result.value!)
and the error:
FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fc39349c4a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://mysite.dev/fb, NSErrorFailingURLKey=http://mysite.dev/fb,
_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
fatal error: unexpectedly found nil while unwrapping an Optional value
So how can I exit the call if the request timed out? preventing it from trying to get the json data
Thanks,
You can increase the timeout interval if your service getting long time.
let request = NSMutableURLRequest(URL: NSURL.init(string: "your url")!)
request.HTTPMethod = "GET"
request.timeoutInterval = 250 // Set your timeout interval here.
Alamofire.request(request).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) { //Check for response
print(responseData.result.value!)
}
}
And must check that the response is not nil to resolve the issue of fatal error.
you need to know more about swift variable unwrapping, just a simple if(myJsonData != nil) would prevent the app crash, you can also add an alert box in case that there is no data on server or the server is down etc...
static func loginWithFb(facebookId: String, email: String, username: String, response: (token: String?, errorVal: JSON?) -> ()) {
let urlString = baseURL + ResourcePath.FbLogin.description
let parameters: [String: AnyObject] = [
"facebook_id": facebookId,
"user_type": 1,
"email": email,
"username": username
]
Alamofire.request(.POST, urlString, parameters: parameters).responseJSON{ (responseData) -> Void in
let myJsonData = JSON(responseData.result.value!)
if(myJsonData != nil)
{
let token = myJsonData["api_key"].string
}
else
{
// show alert box
}
}
}
Your issue is here
let json = JSON(responseData.result.value!)
you are force unwrapping value! instead you should wrap it in an if let
if let json = JSON(responseData.result.value) as? NSDictionary {
let token = json["api_key"].string
response(token: token, errorVal: json)
}
The timeout is fine and is not effecting your app in any way.
I'm trying to send an http request in swift.
I got a method (sendHttpRequest) that take as argument a dictionary<String,AnyObject> and trying to send a request to localhost with a little server in php. When I tap button that call this function an error occur
"Optional(Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSErrorFailingURLStringKey=46.101.145.122/salvobertoncini.com/servo.php, NSErrorFailingURLKey=46.101.145.122/salvobertoncini.com/servo.php, NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x1763cef0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}})"
Here is the code:
func sendHttpRequests(data : Dictionary<String, AnyObject>)
{
let session = NSURLSession.sharedSession()
do
{
let request = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
let url = NSURL ( string : "127.0.0.1/Server/servo.php")
let finalRequest = NSMutableURLRequest(URL: url!)
finalRequest.HTTPMethod = "POST"
finalRequest.HTTPBody = request
let task = session.dataTaskWithRequest(finalRequest){ data,response,error in
if error != nil
{
print("Error -> \(error)")
}
do
{
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result -> \(result)")
}
catch
{
print("Error -> \(error)")
}
}
task.resume()
}
catch
{
print(error)
}
}
I'm working on a passbook capable swift application and i'm in front of a strange problem.
Randomly, the passbook i download from my server is corrupted (the same downloaded can be good or corrupted).
Here is the code :
func openPass(pass: PKPass)
{
let passname = "Benight Ticket"
var passcontroller = PKAddPassesViewController(pass: pass)
passcontroller.delegate = self
self.presentViewController(passcontroller, animated: true, completion: nil)
}
func getTicketPassbook()
{
let TicketID: String = "2gBOZqWwNj"
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: NSURL(string: "https://exemple.com/index.php")!)
request.HTTPMethod = "POST"
let postString: String = "ObjectId=" + TicketID + "&authKey=\"exemple\""
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
println("response = \(response)")
if (error == nil) {
// Success
let statusCode = (response as! NSHTTPURLResponse).statusCode
if (statusCode == 200)
{
println("Success: \(statusCode)")
var pkfile : NSData = NSData(data: data)
var pass: PKPass = PKPass(data: pkfile, error: nil)
self.openPass(pass)
}
// This is your file-variable:
// data
}
else {
// Failure
println("Faulure: %#", error.localizedDescription);
}
})
task.resume()
}
The error is the following : 2015-08-22 16:18:28.328 Application[10302:1018965] BOM could not extract archive: Couldn't read PKZip signature
And other times it works.... It's really at random times that it works or fail...
EDIT : Sometis i've also the following error : 2015-08-23 01:19:19.483 Benight[3467:994898] Invalid data error reading pass pass.com.apple.demo/8j23fm3. The passTypeIdentifier or teamIdentifier provided may not match your certificate, or the certificate trust chain could not be verified.
fatal error: unexpectedly found nil while unwrapping an Optional value
I have implemented this piece of code for basic auth and sometimes doesn't work on first time:
func doRequestWithBasicAuth(completion : (success : Bool, html: String?, error : NSError?) -> Void) {
if let user = self.user {
let loginString = NSString(format: "%#:%#", user.login!, user.pwd!)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
let url = NSURL(string: user.service!.getURL())
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
if error == nil {
let htmlString = NSString(data: data, encoding: NSUTF8StringEncoding)
completion(success: true, html: htmlString as? String, error: nil)
} else {
completion(success: false, html: nil, error: error)
}
}
} else {
completion(success: false, html: nil, error: NSError())
}
}
This method is attached to a button, so on first tap I get this error:
BASIC AUTH ERROR: Error Domain=NSURLErrorDomain Code=-1012 "The
operation couldn’t be completed. (NSURLErrorDomain error -1012.)"
UserInfo=0x7bad5770
{NSErrorFailingURLKey=https:///auth/Logon.do,
NSErrorFailingURLStringKey=https:///auth/Logon.do,
NSUnderlyingError=0x7b9c47f0 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1012.)"}
On second tap, call works fine... I can't understand why.. I print user login, psw and url: are the same on twice calls..
Any idea?
Any idea why sendSynchronousRequest not work, and returns nil. Error and response is nil as well.
let url = NSURL(fileURLWithPath: "http://google.com")!
let ur = NSMutableURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
let errorPtr = NSErrorPointer()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let data = NSURLConnection.sendSynchronousRequest(ur, returningResponse: response, error: errorPtr)
if errorPtr != nil {
var error: NSError = errorPtr.memory!
}
})
UPDATE
I tried in the async way:
var oq = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(ur, queue: oq, completionHandler: {response, data, error in
let ii = 7
})
Here I get an error:
(lldb) po error
Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo=0x1567f9d0 {NSErrorFailingURLStringKey=file:///http:/google.com, NSErrorFailingURLKey=file:///http:/google.com, NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x15691880 "The requested URL was not found on this server."}
Strange google is not available?
You are using fileURLWithPath and that will return the URL
file:///private/var/folders/xs/6k9v2g217155wr9vgb3xrg_80000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-F81D60A5-6797-4BEB-8AB9-2D156E2B6771/http:/google.com
What you need is let url = NSURL(string: "http://google.com")!
and that will return the URL:
http://google.com