Category Archives: alamofire

How to use Alamofire with self signed SSL certificate

I am making a swift application which needs to connect to my local computer, running XAMPP.

The code that I have is the following (swift)

import Alamofire
class UploadHelper
{

    private var _postData = [String:Any]()
    init(username:String) {
        _postData["username"] = username
        print("Setup")
        submitRequest()
    }

    func submitRequest()
    {
        let request = Alamofire.request("https:/192.168.1.243", method: .post, parameters: _postData, encoding: JSONEncoding.default).responseString { (responce) in
            print("Responce: \(responce)")
        }
    }


}

The only problem is when I run let helper = UploadHelper(), I get the following output:

2017-01-29 13:45:02.050321 Network Storage[5305:186605] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) Responce: FAILURE: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.1.243” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, NSErrorPeerCertificateChainKey=( "" ), NSUnderlyingError=0x174053350 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=, _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, kCFStreamPropertySSLPeerCertificates=( "" )}}, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.1.243” which could put your confidential information at risk., NSErrorFailingURLKey=https://192.168.1.243/, NSErrorFailingURLStringKey=https://192.168.1.243/, NSErrorClientCertificateStateKey=0}




Here is my info.plist with the NSAppTransport keys:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowArbitraryLoads</key><true/>
    </dict>
</dict>
</plist>

Finaly, I created my own certificate by using the following instructions: http://superuser.com/questions/73979/how-to-easily-create-a-ssl-certificate-and-configure-it-in-apache2-in-mac-os-x

After I added the certificate, I added the folling lines to my httpd.conf file:

SSLEngine on
SSLCertificateFile /Applications/XAMPP/etc/sslcert/server.crt
SSLCertificateKeyFile /Applications/XAMPP/etc/sslcert/server.key

I also changed Listen 80 to ' Listen 443'.

After all the changes, I restarted XAMPP and went to my server at https://192.168.1.243 and Safari (macOS) alerted me that the certificate was not trusted but contained all the information that I had entered.

How would I be able to connect to my development server on my computer with Alamofire (latest version) on iOS 10.2 with Swift 3.0.2?

Large Image uploading error Using Base 64 string Alarmofire Swift / .Net Services

I have have a strange problem for uploading images the following code works well with small images but when i try to upload large size images if fails with following error 413 Request Entity Too Large ginx/1.6.0 I am using WCF .Net Services with IIS 6/7.

I am creating base 64 string of the image using following method :

func getBase64StringFromImage(anImage: UIImage, enhanceUpto:CGFloat) -> String{

    let imageData = UIImageJPEGRepresentation(anImage, enhanceUpto)
    let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
    //print(base64String)
    return base64String
}

And then the following service call :

if aSenderImageView1.image != nil{
    base64ImageString1 = sABase64ImagetoString.getBase64StringFromImage(aSenderImageView1.image!, enhanceUpto: 1.0)
}
if base64ImageString1.length > 0 {
      finalParamDict = ["Attach":base64ImageString1,"FileName":"Image1.jpeg"]
}
finalParamDict["Email"] = self.emailTxtField.text!
finalParamDict["Mobile"] = mobileNo
finalParamDict["NameEn"] = Defaults["customerName"].string!
finalParamDict["POBox"] = self.addressTxtField.text!
finalParamDict["ID"] = customerQID
finalParamDict["ServiceID"] = serviceID
finalParamDict["VAL1"] = gender

Alamofire.request(.POST,serverUrl ,headers:serviceHeaders,parameters:finalParamDict, encoding:.JSON)
                .responseJSON{
                    response in
                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")
                    }
}

This is the response for larger images mostly larger then 1MB.

Optional(<html>

<head><title>413 Request Entity Too Large</title></head>

<body bgcolor="white">

<center><h1>413 Request Entity Too Large</h1></center>

<hr><center>nginx/1.6.0</center>

</body>

</html>

)

not able to get new content using alamofire (not able to refresh the cache content)

for some reason, I'm not able to take advantage of the cache mechanism that alamofire provides and im forced to clear the cache so I can ge the new json content to be parsed by alamofire.

i checked the control header and etag and i printed out the response and request, but i found something weird. check the max-age. my website uses HTTP:

request <NSMutableURLRequest: 0x7a12b400> { URL: http://www.example.com/wp-json/posts }
response Optional(<NSHTTPURLResponse: 0x7a12fd30> { URL: http://www.example.com/wp-json/posts } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Type" = "application/json; charset=UTF-8";
    Date = "Sat, 26 Sep 2015 18:52:14 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    "Last-Modified" = "Sat, 26 Sep 2015 17:43:31 GMT";
    Link = "</wp-json/posts?page=2>; rel=\"next\", 


    Server = Apache;
    **"Strict-Transport-Security" = "max-age=63072000; includeSubDomains";**
    "Transfer-Encoding" = Identity;
    Vary = "Accept-Encoding,User-Agent";
    "X-Content-Type-Options" = nosniff;
    "X-Frame-Options" = SAMEORIGIN;
    "X-Pingback" = "http://www.example.com/xmlrpc.php";
    "X-Powered-By" = "PHP/5.4.45";
    "X-WP-Total" = 11;
    "X-WP-TotalPages" = 2;
} })

how can I change the max-age and use the reinvalidate control header so that alamofire can know that there is new content on the server and try refresh the cache instead of loading old data?

thanks.

POST request detected as GET on GoDaddy servers with Alamofire

In an iPad app I developed several months ago I created a PHP file that acts as an API. The file simply receives POST data sent from the app and adds it to a database.

This has been working flawlessly for several months, however, as of last week, the app errors out because the API is not detecting POST data. When checking the Raw Access Logs in GoDaddy, I see that the request is being detected as GET instead of POST. When I point the app to the development server API (hosted elsewhere), it works perfectly fine.

There is no .htaccess file on the GoDaddy account as of right now. The account was reset and rebuilt with only the necessary files. Still having the same issue.

I setup a simple <form> on a remote site and set the form's action to the GoDaddy account, with the method set to "post". This works fine, so this tells me that external POST data should be allowed. The access logs show these requests with as POST 200. Yet the app's requests are coming in as GET 200.

My code for the request in Swift / Alamofire looks like this:

Alamofire.request(.POST, "http://www.WEBSITE.com/app/api.php", parameters:parameters).responseJSON { (req, res, response, error) in
    if(error != nil){
        println(error?.localizedDescription)
    }
    else {
        //...
    }
}

I have contacted GoDaddy and spent hours on the phone with them. They have ensured me that nothing on the account or the domain is out of the ordinary, and that they have not updated any of their security policies in several months.

I'm at a loss. I'm not sure why this isn't working so suddenly. It's been working perfectly since deployment back in February (4 months ago).

On the API the first check is if($_POST){} which is where it fails. Again, everything works flawlessly on another server.

The Access Logs:

GoDaddy Server "GET /app/api.php HTTP/1.1" 200 15 "-" "Waiver/ca.grumpygoat.Waiver (1; OS Version 8.3 (Build 12F69))"

Development Server "POST /sandbox/iOS/waiver/api.php HTTP/1.1" 200 195 "-" "Waiver/ca.grumpygoat.Waiver (1; OS Version 8.3 (Build 12F69))"