#NSMutableURLRequest
Explore tagged Tumblr posts
Text
WebServices Using Swift
// WebServiceClass.swift
// webService
// Created by Bhushan on 24/07/18.
// Copyright © 2018 Bhushan. All rights reserved.
import UIKit
typealias completionService = (_ data: Data, _ response: URLResponse, _ error: Error?) -> Void
class WebServiceClass: NSObject {
override init() {
super.init()
}
func sendGetRequest(_ dictionary: [AnyHashable: Any], withMethod method: String, withCompletion block:@escaping completionService) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(url: URL(string: method)!)
request.httpMethod = "GET"
let dataTask = session.dataTask(with: request as URLRequest) { (data,response,error) in
if error != nil{
print(error!.localizedDescription)
if block != nil {
let tempData : Data = Data()
let tempResponse : URLResponse = URLResponse()
block(tempData, tempResponse, error)
} }
else {
if block != nil {
block(data!, response!, error)
}
}
}
dataTask.resume()
}
func sendPostRequest(_ dictionary: [AnyHashable: Any], withMethod method: String, withCompletion block: @escaping completionService) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(url: URL(string: method)!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postData: Data? = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
request.httpBody = postData
// request.httpBody = postData
let dataTask = session.dataTask(with: request as URLRequest) { (data,response,error) in
if error != nil{
print(error!.localizedDescription)
if block != nil {
let tempData : Data = Data()
let tempResponse : URLResponse = URLResponse()
block(tempData, tempResponse, error)
}
// return
}
else {
if block != nil {
block(data!, response!, error)
}
}
}
dataTask.resume()
}
***Important Links***
http://images.nuptial.me/ProfilePics/Wedding1/ProfilePicForPartner1.png http://images.nuptial.me/WedsiteImages/Wedsite1/WedsiteImageForWedding1/WedsiteImage11198175568T1530284086.jpg
http://aerialyoga_api.dedicatedresource.net/login email, password , device_type
http://aerialyoga_api.dedicatedresource.net/about-us
***To Download Image***
func downloadImage(url: URL, withImage imageView:UIImageView) {
print("Download Started")
// var actInd: UIActivityIndicatorView = UIActivityIndicatorView()
// showActivityIndicatory(imgView: imageView, and: actInd)
getDataFromUrl(url: url) { (data, response, error) in
guard error == nil else { return }
print(response.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
// actInd.stopAnimating()
imageView.image = UIImage(data: data)
}
}
}
***Hints About Post Method***
func inviteeLogin(){
if isValidated(){
showLoader(OnView: view)
let serviceHandler: ServiceHandler = ServiceHandler()
let postString = "Invitees[INVITEE_EMAIL]=\(txtEmailField.text!)&Invitees[PIN_CODE]=\(txtEnterCode.text!)"
serviceHandler.sendPostRequestWithString(postString, withMethod: "http://rest.nuptial.me/wedsite-couple/login", withCompletion:{(_ data: Data, _ response: URLResponse, _ error: Error?) -> Void in
if error == nil {
do{
let dic = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]
if ((dic?["status"] as! Int) == 1) {
DispatchQueue.main.async(execute: {() -> Void in
self.dismissLoader()
print(dic!)
let dict = dic!["data"] as! [String:AnyObject]
NPConstants.defaults.set(dict["INVITEE_ID"], forKey: "inviteeId")
NPConstants.defaults.synchronize()
let controller = self.storyboard?.instantiateViewController(withIdentifier: "NPInviteeVC") as! NPInviteeVC
self.navigationController?.pushViewController(controller, animated: true)
})
}
else
{
DispatchQueue.main.async(execute: {() -> Void in
print(dic!)
self.dismissLoader()
})
}
}
catch{
self.dismissLoader()
print("catch block")
print("Error with Json: \(error)")
}
}
else {
DispatchQueue.main.async(execute: {() -> Void in
self.dismissLoader()
})
}
})
}
}
0 notes
Text
iOS Cookie Maintenance
Based on using Android volley to connect to Windows IIS, for iOS, it would be easier to maintain a cookie from server side.
If you are using this library – AFNetworking, basically, you don’t need to worry about cookie handling.
/** Whether created requests should use the default cookie handling. `YES` by default. @see NSMutableURLRequest -setHTTPShouldHandleCookies: */ @property (nonatomic,…
View On WordPress
0 notes
Text
Setting NSMutableURLRequest Cookies
I've been looking for a easy a simple explanation/tutorial of how to add cookies to a NSMutableURLRequest. After experimenting and reading a few forums and blogs, I finally understand how to do it and therefore, I decided to sumarized this in a way I would like someone to explain it to me.
There are two ways you can set cookies. The first one makes use of the setValue function of the NSMutableURLRequest instance. It basically requires you to create a string with the following format COOKIE_NAME_1=COOKIE_VALUE_1 and set it as a header. If you want to add multiple cookies, use a semicolon (;) to separate them. This is what your code would look like:
var request = NSMutableURLRequest(URL: NSURL(string: "http://example.com")) request.setValue( "cookie_name_1=cookie_value1; cookie_name2=cookie_value_2", forHTTPHeaderField: "Cookie")
As you can see is very simple.
The second way seems a bit less simple but it does not involve creating a string with a specific format. In this case, each cookie is defined by a NSHTTPCookie instance. Here is a snippet of what the code would look like:
var request = NSMutableURLRequest(URL: NSURL(string: "http://example.com")) // Cookie1 properties var cookieProperties1 = [ NSHTTPCookieOriginURL: "http://example.com", NSHTTPCookiePath: "/", NSHTTPCookieName: "cookie_name_1", NSHTTPCookieValue: "cookie_value1"] // Create an instance of NSHTTPCookie for cookie1 var cookie1 = NSHTTPCookie.cookieWithProperties(cookieProperties1) // Cookie2 properties var cookieProperties2 = [ NSHTTPCookieOriginURL: "http://example.com", NSHTTPCookiePath: "/", NSHTTPCookieName: "cookie_name_2", NSHTTPCookieValue: "cookie_value2"] // Create an instance of NSHTTPCookie for cookie2 var cookie2 = NSHTTPCookie.cookieWithProperties(cookieProperties2) // Create an array of cookies var cookies[NSHTTPCookie] = [cookie1, cookie2] // Create cookies as headers var cookieHeaders = NSHTTPCookie.requestHeaderFieldsWithCookies(httpCookies) // Set cookies as part of the request header request.allHTTPHeaderFields = cookieHeaders
The first thing you do is to create a dictionary that contains the cookie properties. Once you have that, you create an instance of NSHTTPCookie by calling the cookieWithProperties function and passing the properties dictionary. Repeat this process for each cookie you want to set and append it to an array. Once you are done, use the requestHeaderFieldsWithCookies function to create the cookie headers. Last, assign the cookie headers to the request by using the allHTTPHeaderFields attribute.
NOTE: Assigning the cookies using allHTTPHeaderFields function, will override the previous headers you may have set using the addValue function. If you want to set headers to the request, do it after you set cookies if you are using the second way.
I hope you find this useful. Cheers.
1 note
·
View note