I am new in swift and i am implement one demo in which i have dictionary with multiple object in which there are some UIImage objects.
How i can differentiate UIImage object? I am using isKindClass but it is not work for me and give the error like "'AnyObject' dose not have member name isKindOfClass"
Code is like this
func initURLConnectionWithRequest(requestUrl:NSURL,apiTag:NSInteger,paramDic:NSDictionary,obj:NSObject) ->IMDRequest
{
var newRequest = IMDRequest()
request1 = newRequest;
self.tag=apiTag
var request = NSMutableURLRequest(URL: requestUrl)
var timeInterval = NSTimeInterval(60)
request.timeoutInterval = timeInterval
request.HTTPMethod = "POST"
var strBoundry = "---------------------------14737809831466499882746641449"
var contentType = "multipart/form-data; boundary=\(strBoundry)"
request.addValue(contentType, forHTTPHeaderField:"Content-Type")
var bodyData = NSMutableData()
var arrParamKey = paramDic.allKeys
for var i = 0; i<arrParamKey.count; i++
{
if (paramDic.objectForKey(arrParamKey[i]).isKindOfClass(UIImage))
{
}
}
urlConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
self.senderObj = obj;
urlConnection.start()
self.isResponseReceived = false
return request1;
}
If you want to check whether the variable is of a type that you want, or that it conforms to some protocol, then you can use this as a reference:
var abc = …
if abc is <UIImage> {
//the variable is of type <UIImage>
} else {
//variable is not of type <UIImage>
}
This is same as isKindOfClass in Objective-C.
Hope this will help you.
Related
I used this code for downloading multiple assets concurrently, but
once in a while the code fail.
I added retry for this call, but this does not feel like a good solution.
any idea why the call for downloadTask fails?
Is there some kind of limitations, like number of concurrent task?
or should I use specific queue?
#objc class Downloader : NSObject {
#objc var fileUrl:URL
#objc var destinationUrl:URL
#objc var dispachGroup:DispatchGroup?
#objc var optionalAsset:Bool
#objc var retryCalled:Int
var downloadTask:URLSessionDownloadTask? = nil
#objc init(dispachGroup:DispatchGroup,fileURL: URL , destinationFileUrl: URL, optionalAsset:Bool) {
self.dispachGroup = dispachGroup
self.fileUrl = fileURL
self.destinationUrl = destinationFileUrl
self.optionalAsset = optionalAsset
self.retryCalled = 0
}
#objc func stop() {
downloadTask?.cancel()
}
#objc func preformDownload(delegate:URLSessionDownloadDelegate, delay:TimeInterval, timeout:TimeInterval) {
let sessionConfig = URLSessionConfiguration.default
let operationQueue = OperationQueue()
let urlSession = URLSession(configuration: sessionConfig, delegate: delegate, delegateQueue: operationQueue)
var request = URLRequest(url: self.fileUrl)
request.timeoutInterval = timeout
self.downloadTask?.cancel()
self.downloadTask = urlSession.downloadTask(with: request)
self.downloadTask?.resume()
}
}
I'm developing an iOS app with Xcode and Swift.
I'm getting JSON data with SwiftyJSON.swift and the following code:
import UIKit
class ViewController: UIViewController {
var dict = NSDictionary()
#IBOutlet weak var firstLb: UILabel!
#IBOutlet weak var secondLb: UILabel!
var uasername = "TestUserName"
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "http://example.com/showUserInfo.php"
if let url = NSURL(string: urlString) {
if let data = try? NSData(contentsOfURL: url, options: []) {
let json = JSON(data: data)
print(json)
let f = json[0]["name"].stringValue
let s = json[0]["age"].stringValue
firstLb.text = f
secondLb.text = s
}
}
}
}
But I want to be able to POST a value to showUserInfo.php, too.
My showUserInfo.php PHP script looks like this:
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";
$username = $_POST['username'];
$stmt = $pdo->prepare('SELECT * FROM contact WHERE username = :username');
$stmt->execute(array('username' => $username));
$userData = array();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$userData[] = $row;
}
echo json_encode($userData);
?>
Getting JSON data from the PHP script with my Swift code works very well when using $username = "TestUserName"; instead of $username = $_POST['username']; in my PHP script. But I want to be able to $_POST a specific username to this PHP script that is declared in my app.
Does anybody know how to do this without the need of importing a library or so?
Here is Alamofire and SwiftyJSON implementation
let parameters = ["username": "TestUserName"]
Alamofire.request(.POST, "http://example.com/showUserInfo.php",parameters: parameters).responseJSON { response in
debugPrint(response.result.value)
let json = JSON(data: response.data!)
print(json)
let f = json[0]["name"].stringValue
let s = json[0]["age"].stringValue
firstLb.text = f
secondLb.text = s
}
In default behaviour NSURL uses GET as a HTTP method. You have to use NSMutableURLRequest and set property called HTTPMethod to POST. If you want to see exactly example of using post request in Swift 2/3 visit here.
I am not able assign the values for var backgroundArray and var newsArray, as the fetch method returns nil. Within the fetch the values are available though. Also, is it a good way to refresh the cache by removing it such way in the commented section?
init(update: Bool){
let dataurl = "http://example.com"
let imgurl = "http://example.com"
let newsDataURL = NSURL(string: dataurl)!
let backgroundURL = NSURL(string: imgurl)!
var backgroundArray = [JSON]()
var newsArray = [JSON]()
let cache = Shared.JSONCache
// if update{
// cache.remove(key: dataurl)
// cache.remove(key: imgurl)
// }
cache.fetch(URL: newsDataURL).onSuccess { json in
let data = json.asData()
newsArray = JSON(data: data).arrayValue
}
cache.fetch(URL: backgroundURL).onSuccess{ json in
let data = json.asData()
backgroundArray = JSON(data: data).arrayValue
}
populateStories(newsArray, backgroundArray: backgroundArray)
}
I have a drug class which I would like to init by passing in a upc: Int. Inside the init I'd like to make a web service call, and populate the values in the class with the returned JSON (NSDictionary).
I have a start, but not a finish. I'm getting errors everywhere and can't seem to figure out how to best accomplish this. Maybe I'm going about this the whole wrong way. Could someone help?
Here's the code ..
init(upc: Int) {
let apiKey = "xx"
let baseURL = NSURL(string: "http://something.com/\(apiKey)/")
let getDrugByUpcURL = NSURL(string: "\(upc).json", relativeToURL: baseURL)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let usernamePasswordString = "user:pass"
let usernamePasswordData = usernamePasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = usernamePasswordData!.base64EncodedStringWithOptions(nil)
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization": authString]
let session = NSURLSession(configuration: config)
let downloadTask: NSURLSessionDownloadTask = session.downloadTaskWithURL(getDrugByUpcURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
let dataObject = NSData(contentsOfURL: location)
println(dataObject)
let drugDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
println(drugDictionary["din"])
drug_id = drugDictionary["drug_id"] as Int
din = drugDictionary["din"] as String
packsize = drugDictionary["packsize"] as Double
brand = drugDictionary["brand"] as String
//generic = drugDictionary["generic"] as String
strength = drugDictionary["strength"] as String
form = drugDictionary["form"] as String
upc = drugDictionary["upc"] as String
//priceGroup = drugDictionary["price_group"] as String
//manufacturer = drugDictionary["manufacturer"] as String
onHandQuantity = drugDictionary["onhand"] as Double
//vendorCost = drugDictionary["vendor_cost"] as Double
//basePrice = drugDictionary["base_price"] as Double
//discount = drugDictionary["discount"] as Double
//price = drugDictionary["price"] as Double
} else {
println(error)
}
})
downloadTask.resume()
}
An error I'm getting is on all property assignment lines: Cannot assign to 'drug_id' in 'self'.
The problem is that you are accessing those instance variables from a closure, the completion handler of downloadTaskWithURL:.
This is easily fixed by prefixing the variables with self.. So drug_id becomes self.drug_id.
Note however that what you are doing in the above code is probably a bad idea. Or at least a very uncommon design: I don't think it is a good idea to do asynchronous network requests in your class' initializer.
Since the call to NSURLSessionDownloadTask is asynchronous, your init() will return immediately with uninitialized data and then at some unspecified moment in time your class will be fully populated with the result from the web service call. You don't know what that moment in time is though, so you really have no good way of knowing when your instance is ready.
This is most likely not what you had in mind.
var friendRQ: FBRequest = FBRequest(forGraphPath: "me/taggable_friends?fields=name,picture.width(66).height(66)")
friendRQ.startWithCompletionHandler({ (Connection, results, error) -> Void in
self.FBData = results.objectForKey("data") as NSMutableArray
println(self.FBData)
})
I have no problem on retrieve the name, but picture.
FBData.picture reutrns a NSURL
picture = {
data = {
height = 68;
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpa1/v/t1.0-1/c9.0.68.68/p68x68/10410849_1410555062563816_XXXXX70293207008499_n.jpg?oh=ddd9e2d36cc13bc0095b243097a199b4&oe=54FC0162&__gda__=1427125899_dc78acc5e14b7d25aee153ccf8bb1543";
width = 68;
};
};
how can I show this picture properly in an ImageView?
var picture: NSURL = FBFriendHelper.sharedInstance.FBData[indexPath.row].picture
var data: AnyObject? = picture.valueForKey("data")
and then?
var FBpicture: NSURL = FBHelper.sharedInstance.FBData[indexPath.row].picture
var url: NSURL = NSURL(string: String(FBpicture.valueForKey("data")?.url! as NSString) as String)!
var picData: NSData = NSData(contentsOfURL: url)!
cell.FBProfile.image = UIImage(data: picData)
I found the solution of mine code